<?php
require_once __DIR__ . '/../../inc/auth.php';
require_once __DIR__ . '/../../inc/functions.php';
$session = auth_require('owner', 'engineer');

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !auth_csrf_verify($_POST['csrf_token'] ?? '')) {
    header('Location: /service/pages/engineer/tasks.php');
    exit;
}

$pdo = getDB();
$userId = $session['user_id'];

// Calculate KPI for each engineer
$engineers = $pdo->query("SELECT id, full_name FROM users WHERE role IN ('engineer','technician') AND is_active")->fetchAll();
$periodStart = date('Y-m-01');
$periodEnd = date('Y-m-t');

// Previous period dates
$prevPeriodStart = date('Y-m-01', strtotime('-1 month'));
$prevPeriodEnd = date('Y-m-t', strtotime('-1 month'));

foreach ($engineers as $eng) {
    $eid = $eng['id'];

    // ---- Individual KPI (Engineer Score) ----

    // SLA compliance
    $stmt = $pdo->prepare("SELECT COUNT(*) as total, SUM(CASE WHEN sla_compliant=TRUE THEN 1 ELSE 0 END) as compliant FROM tasks WHERE assigned_to=$1 AND closed_at IS NOT NULL AND closed_at >= $2");
    $stmt->execute([$eid, $periodStart]);
    $sd = $stmt->fetch();
    $slaCompliance = calc_sla_compliance((int)($sd['compliant'] ?? 0), (int)($sd['total'] ?? 0));

    // Response time score
    $stmt = $pdo->prepare("SELECT AVG(response_time_minutes) as avg_rt FROM tasks WHERE assigned_to=? AND closed_at IS NOT NULL AND closed_at >= ?");
    $stmt->execute([$eid, $periodStart]);
    $rt = (float)($stmt->fetchColumn() ?: 0);
    $responseTimeScore = calc_response_time_score($rt / 60, 4);

    // Resolution time score
    $stmt = $pdo->prepare("SELECT AVG(resolution_time_minutes) as avg_ttr FROM tasks WHERE assigned_to=? AND closed_at IS NOT NULL AND closed_at >= ?");
    $stmt->execute([$eid, $periodStart]);
    $ttr = (float)($stmt->fetchColumn() ?: 0);
    $resolutionTimeScore = calc_resolution_time_score($ttr / 60, 8);

    // Diagnosis accuracy
    $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM reports WHERE created_by=? AND created_at >= ?");
    $stmt->execute([$eid, $periodStart]);
    $reportTotal = (int)$stmt->fetchColumn();
    $diagnosisAccuracy = $reportTotal > 0 ? 85 : 75;

    // Reopen rate
    $stmt = $pdo->prepare("SELECT COUNT(*) as reopened FROM tasks WHERE assigned_to=? AND status='completed' AND closed_at IS NOT NULL AND closed_at >= ? AND checklist_data LIKE '%\"fault_found\":1%'");
    $stmt->execute([$eid, $periodStart]);
    $reopened = (int)$stmt->fetchColumn();
    $totalTasks = max(1, $sd['total'] ?? 1);
    $reopenRate = calc_reopen_rate($reopened, $totalTasks);
    $reopenRateScore = max(0, 100 - $reopenRate * 2);

    // Risk coverage score
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM reports WHERE created_by=? AND created_at >= ? AND findings IS NOT NULL AND findings != ''");
    $stmt->execute([$eid, $periodStart]);
    $goodReports = (int)$stmt->fetchColumn();
    $riskCoverageScore = calc_risk_coverage($goodReports, $reportTotal ?: 1);

    // Documentation quality
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM reports WHERE created_by=? AND created_at >= ? AND status='final'");
    $stmt->execute([$eid, $periodStart]);
    $fullReports = (int)$stmt->fetchColumn();
    $docQuality = calc_documentation_quality($fullReports, $reportTotal ?: 1);

    // Engineer score
    $es = calc_engineer_score($slaCompliance, $responseTimeScore, $resolutionTimeScore, $diagnosisAccuracy, $reopenRateScore, $riskCoverageScore);
    $grade = engineer_grade($es);

    // ---- ECS (Engineer Control Score) — для инженеров, управляющих техниками ----
    $ecs = null;
    $ecsComponents = null;

    // Get objects where this engineer is assigned
    $stmt = $pdo->prepare("SELECT object_id FROM object_assignments WHERE user_id=? AND role='engineer' AND unassigned_at IS NULL");
    $stmt->execute([$eid]);
    $engObjectIds = $stmt->fetchAll(PDO::FETCH_COLUMN);

    if (!empty($engObjectIds)) {
        $placeholders = implode(',', array_fill(0, count($engObjectIds), '?'));

        // ECS 1: SLA Control — SLA compliance on tasks across all objects under this engineer
        $stmt = $pdo->prepare("SELECT COUNT(*) as total, SUM(CASE WHEN sla_compliant=TRUE THEN 1 ELSE 0 END) as compliant FROM tasks WHERE object_id IN ($placeholders) AND closed_at IS NOT NULL AND closed_at >= $". (count($engObjectIds) + 1));
        $params = $engObjectIds;
        $params[] = $periodStart;
        $stmt->execute($params);
        $slaCtrl = $stmt->fetch();
        $slaControl = $slaCtrl['total'] > 0 ? ($slaCtrl['compliant'] / $slaCtrl['total']) * 100 : 100;

        // ECS 2: Task Distribution — load balance among technicians on these objects
        $stmt = $pdo->prepare("SELECT assigned_to, COUNT(*) as cnt FROM tasks WHERE object_id IN ($placeholders) AND assigned_to IS NOT NULL AND closed_at >= ? GROUP BY assigned_to");
        $params2 = $engObjectIds;
        $params2[] = $periodStart;
        $stmt->execute($params2);
        $taskDistData = $stmt->fetchAll();
        $tasksPerTech = array_column($taskDistData, 'cnt');
        $taskDist = count($tasksPerTech) > 1 ? max(0, 100 - calc_tlb($tasksPerTech)) : 100;

        // ECS 3: Incident Reduction — compare current vs prev month incidents on these objects
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM incidents WHERE object_id IN ($placeholders) AND created_at >= ? AND created_at <= ?");
        $curParams = $engObjectIds;
        $curParams[] = $periodStart;
        $curParams[] = $periodEnd;
        $stmt->execute($curParams);
        $currentInc = (int)$stmt->fetchColumn();

        $prevParams = $engObjectIds;
        $prevParams[] = $prevPeriodStart;
        $prevParams[] = $prevPeriodEnd;
        $stmt->execute($prevParams);
        $prevInc = (int)$stmt->fetchColumn();

        $incidentRed = calc_incident_reduction($prevInc, $currentInc);
        if ($prevInc === 0 && $currentInc === 0) $incidentRed = 100;

        // ECS 4: Team Performance — avg engineer_score of technicians on these objects
        $techScoreSum = 0;
        $techScoreCount = 0;
        foreach ($taskDistData as $td) {
            $techId = (int)$td['assigned_to'];
            $stmt = $pdo->prepare("SELECT AVG(engineer_score) FROM engineer_kpi WHERE engineer_id=$1 AND period_end > NOW() - INTERVAL '30 days'");
            $stmt->execute([$techId]);
            $ts = (float)$stmt->fetchColumn();
            if ($ts > 0) {
                $techScoreSum += $ts;
                $techScoreCount++;
            }
        }
        $teamPerf = $techScoreCount > 0 ? $techScoreSum / $techScoreCount : 70;

        // ECS 5: Response Coordination — avg response time score across object tasks
        $stmt = $pdo->prepare("SELECT AVG(response_time_minutes) as avg_rt FROM tasks WHERE object_id IN ($placeholders) AND closed_at IS NOT NULL AND closed_at >= ? AND response_time_minutes > 0");
        $respParams = $engObjectIds;
        $respParams[] = $periodStart;
        $stmt->execute($respParams);
        $avgRespTime = (float)($stmt->fetchColumn() ?: 0);
        $responseCoord = calc_response_time_score($avgRespTime / 60, 4);

        $ecs = calc_engineer_control_score($slaControl, $taskDist, $incidentRed, $teamPerf, $responseCoord);

        $ecsComponents = [
            'sla_control'    => round($slaControl, 1),
            'task_dist'      => round($taskDist, 1),
            'incident_red'   => round($incidentRed, 1),
            'team_perf'      => round($teamPerf, 1),
            'response_coord' => round($responseCoord, 1),
        ];
    }

    // Save
    $components = [
        'sla_compliance'       => $slaCompliance,
        'response_time_score'  => $responseTimeScore,
        'resolution_time_score'=> $resolutionTimeScore,
        'diagnosis_accuracy'   => $diagnosisAccuracy,
        'reopen_rate'          => $reopenRate,
        'risk_coverage_score'  => $riskCoverageScore,
        'doc_quality'          => $docQuality,
        'ecs'                  => $ecs,
        'ecs_components'       => $ecsComponents,
    ];

    $stmt = $pdo->prepare("INSERT INTO engineer_kpi (engineer_id, period_start, period_end, sla_compliance, response_time_score, resolution_time_score, diagnosis_accuracy, reopen_rate, risk_coverage_score, documentation_quality, engineer_score, grade, components_json)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
    $stmt->execute([
        $eid, $periodStart, $periodEnd,
        $slaCompliance, $responseTimeScore, $resolutionTimeScore,
        $diagnosisAccuracy, $reopenRate, $riskCoverageScore, $docQuality,
        $es, $grade,
        json_encode($components)
    ]);
}

$logMsg = 'KPI calculated for ' . count($engineers) . ' users';
$ecsCount = 0;
foreach ($engineers as $eng) {
    $stmt = $pdo->prepare("SELECT components_json FROM engineer_kpi WHERE engineer_id=? AND period_start=? ORDER BY id DESC LIMIT 1");
    $stmt->execute([$eng['id'], $periodStart]);
    $row = $stmt->fetch();
    if ($row) {
        $comp = json_decode($row['components_json'], true);
        if (!empty($comp['ecs'])) $ecsCount++;
    }
}
if ($ecsCount > 0) $logMsg .= " (ECS calculated for $ecsCount engineers)";

auth_log($userId, 'kpi_calc', $logMsg);
header('Location: /service/pages/owner/ceo.php?kpi_ok=1');
exit;
