<?php

ob_start();

require_once __DIR__ . '/../../core/config.php';
require_once __DIR__ . '/../../core/session.php';
require_once __DIR__ . '/../../core/permissions.php';
require_once __DIR__ . '/../../services/analytics/DashboardAccessService.php';
require_once __DIR__ . '/../../services/analytics/KpiDashboardService.php';
require_once __DIR__ . '/../../services/analytics/KpiTargetService.php';

function dashboard_target_response($payload, $status = 200)
{
    while (ob_get_level() > 0) ob_end_clean();
    http_response_code((int)$status);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function dashboard_target_valid_date($value)
{
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', (string)$value)) return false;
    $date = DateTime::createFromFormat('!Y-m-d', (string)$value);
    return $date && $date->format('Y-m-d') === $value;
}

try {
    require_login();
    $user = current_user();
    $method = strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET'));
    if (!in_array($method, array('GET', 'POST'), true)) {
        dashboard_target_response(array('success' => false, 'message' => 'Método no permitido.'), 405);
    }
    if ($method === 'POST') csrf_require_valid_request();

    $input = $method === 'POST' ? $_POST : $_GET;
    $view = trim((string)($input['view'] ?? ''));
    $kpiId = trim((string)($input['kpi_id'] ?? ''));
    $from = trim((string)($input['from'] ?? date('Y-m-01')));
    $to = trim((string)($input['to'] ?? date('Y-m-t')));

    if (!dashboard_target_valid_date($from) || !dashboard_target_valid_date($to) || $from > $to) {
        dashboard_target_response(array('success' => false, 'message' => 'El período solicitado no es válido.'), 422);
    }

    $access = new DashboardAccessService();
    $catalog = $access->catalog();
    if (!isset($catalog[$view])) {
        dashboard_target_response(array('success' => false, 'message' => 'El dashboard solicitado no existe.'), 404);
    }
    if (!$access->canView($view, $user)) {
        dashboard_target_response(array('success' => false, 'message' => 'No tienes acceso a este dashboard.'), 403);
    }
    if (!$access->canConfigure($view, $user)) {
        dashboard_target_response(array('success' => false, 'message' => 'No tienes permisos para configurar metas en este dashboard.'), 403);
    }

    $dashboardService = new KpiDashboardService($from, $to, $user);
    $dashboard = $dashboardService->getDashboard($view);
    $selectedKpi = null;
    foreach ($dashboard['kpis'] as $kpi) {
        if ((string)$kpi['id'] === $kpiId) {
            $selectedKpi = $kpi;
            break;
        }
    }
    if (!$selectedKpi) {
        dashboard_target_response(array('success' => false, 'message' => 'El KPI no pertenece a este dashboard.'), 404);
    }

    $targetService = new KpiTargetService();
    if ($method === 'GET') {
        $target = $targetService->findForPeriod($kpiId, $from, $to, true);
        dashboard_target_response(array(
            'success' => true,
            'kpi' => array(
                'id' => $selectedKpi['id'],
                'name' => $selectedKpi['name'],
                'unit' => $selectedKpi['unit'],
                'direction' => $selectedKpi['favorable_direction'] ?? 'informative',
                'suggested_target' => $selectedKpi['target'],
            ),
            'target' => $target,
            'defaults' => array('period_from' => $from, 'period_to' => $to, 'status' => 'draft'),
        ));
    }

    $saved = $targetService->saveCompanyTarget(array(
        'target_id' => $input['target_id'] ?? null,
        'kpi_id' => $kpiId,
        'period_from' => $input['period_from'] ?? $from,
        'period_to' => $input['period_to'] ?? $to,
        'target_value' => $input['target_value'] ?? null,
        'amber_threshold' => $input['amber_threshold'] ?? null,
        'red_threshold' => $input['red_threshold'] ?? null,
        'status' => $input['status'] ?? 'draft',
        'notes' => $input['notes'] ?? null,
    ), (int)$user['id'], $view);

    dashboard_target_response(array(
        'success' => true,
        'message' => $saved['status'] === 'approved'
            ? 'Meta aprobada y aplicada al KPI.'
            : ($saved['status'] === 'inactive' ? 'Meta marcada como inactiva.' : 'Meta guardada como borrador.'),
        'target' => $saved,
    ));
} catch (InvalidArgumentException $e) {
    dashboard_target_response(array('success' => false, 'message' => $e->getMessage()), 422);
} catch (Throwable $e) {
    error_log('dashboard kpi target error: ' . $e->getMessage());
    dashboard_target_response(array('success' => false, 'message' => 'No fue posible guardar la meta. Verifica que la migración v8.7 esté aplicada.'), 500);
}
