<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Database;
use App\Core\Permission;
use App\Core\Router;
use App\Models\Kpi;
use App\Models\Lookup;

class KpiController
{
    /** Admin: company-wide KPI dashboard, filterable by department (all departments visible). */
    public function adminDashboard(): void
    {
        $admin = Permission::requireSuperAdmin();
        $departments = Lookup::departments();
        $selectedDeptId = (int)($_GET['dept'] ?? ($departments[0]['id'] ?? 0));
        $periodStart = $_GET['week'] ?? Kpi::currentWeekStart();

        $metrics = $selectedDeptId ? Kpi::metricsForDepartment($selectedDeptId) : [];
        $entries = $selectedDeptId ? Kpi::entriesForDepartment($selectedDeptId, $periodStart) : [];

        require __DIR__ . '/../Views/admin/kpi_dashboard.php';
    }

    /** Admin: configure which KPI fields exist per department. */
    public function adminSetup(): void
    {
        $admin = Permission::requireSuperAdmin();
        $departments = Lookup::departments();
        $selectedDeptId = (int)($_GET['dept'] ?? ($departments[0]['id'] ?? 0));
        $metrics = $selectedDeptId ? Kpi::metricsForDepartment($selectedDeptId) : [];

        $flash = $_SESSION['flash'] ?? null;
        unset($_SESSION['flash']);

        require __DIR__ . '/../Views/admin/kpi_setup.php';
    }

    public function adminSetupSave(): void
    {
        Permission::requireSuperAdmin();
        $deptId = (int)($_POST['department_id'] ?? 0);
        $labels = $_POST['label'] ?? [];
        $units = $_POST['unit'] ?? [];
        $types = $_POST['type'] ?? [];

        $metrics = [];
        foreach ($labels as $i => $label) {
            $metrics[] = ['label' => $label, 'unit' => $units[$i] ?? '', 'type' => $types[$i] ?? 'number'];
        }

        Kpi::saveMetricDefs($deptId, $metrics);

        $actor = Auth::currentUser();
        \App\Core\AuditLog::record($actor['user_type'], $actor['user_id'], $actor['name'], 'kpi_setup', (string)$deptId, 'update');

        $_SESSION['flash'] = ['type' => 'success', 'msg' => 'KPI fields updated for this department.'];
        Router::redirect('/admin/kpi/setup?dept=' . $deptId);
    }

    /** Workspace: manager/employee KPI entry + their own submission history, scoped to their assigned departments. */
    public function workspaceKpi(): void
    {
        $user = Permission::requireLogin();

        if ($user['is_super_admin']) {
            Router::redirect('/admin/kpi');
        }

        $departments = Lookup::departmentsForUser($user['user_type'], $user['user_id']);
        $selectedDeptId = (int)($_GET['dept'] ?? ($departments[0]['id'] ?? 0));
        $periodStart = $_GET['week'] ?? Kpi::currentWeekStart();

        $hasAccess = false;
        foreach ($departments as $d) { if ((int)$d['id'] === $selectedDeptId) $hasAccess = true; }

        $metrics = [];
        $myEntry = null;
        $history = [];

        if ($hasAccess) {
            $metrics = Kpi::metricsForDepartment($selectedDeptId);
            $myEntry = Kpi::myEntry($selectedDeptId, $user['user_type'], $user['user_id'], $periodStart);

            $db = Database::connection();
            $stmt = $db->prepare(
                "SELECT * FROM kpi_entries WHERE department_id=:d AND user_type=:t AND user_id=:u ORDER BY period_start DESC LIMIT 8"
            );
            $stmt->execute(['d' => $selectedDeptId, 't' => $user['user_type'], 'u' => $user['user_id']]);
            $history = $stmt->fetchAll();
            foreach ($history as &$h) { $h['values'] = json_decode($h['values_json'], true) ?: []; }
        }

        require __DIR__ . '/../Views/workspace/kpi.php';
    }

    public function workspaceKpiSubmit(): void
    {
        $user = Permission::requireLogin();
        $deptId = (int)($_POST['department_id'] ?? 0);
        $periodStart = $_POST['period_start'] ?? Kpi::currentWeekStart();

        // confirm this user is actually assigned to the department they're submitting for
        $departments = Lookup::departmentsForUser($user['user_type'], $user['user_id']);
        $allowed = array_column($departments, 'id');
        if (!in_array($deptId, $allowed, true) && !$user['is_super_admin']) {
            http_response_code(403);
            echo 'You are not assigned to this department.';
            return;
        }

        $metrics = Kpi::metricsForDepartment($deptId);
        $values = [];
        foreach ($metrics as $m) {
            $values[$m['metric_key']] = trim($_POST['metric'][$m['metric_key']] ?? '');
        }

        Kpi::saveEntry($deptId, $user['user_type'], $user['user_id'], $user['name'], $periodStart, $values);

        \App\Core\AuditLog::record($user['user_type'], $user['user_id'], $user['name'], 'kpi_entry', (string)$deptId, 'update');

        $_SESSION['flash'] = ['type' => 'success', 'msg' => 'KPI entry submitted for this week.'];
        Router::redirect('/kpi?dept=' . $deptId . '&week=' . $periodStart);
    }
}
