<?php

namespace App\Controllers;

use App\Core\Permission;
use App\Core\Router;
use App\Models\CesarKpi;
use App\Models\ActivityLog;

class CesarKpiController
{
    // ─── Index: redirect to the right view ─────────────────────────────────────

    public function index(): void
    {
        $user = Permission::requireLogin();

        if (CesarKpi::canSubmit($user)) {
            Router::redirect('/projects/cesar-kpi/my-records');
            return;
        }
        if (CesarKpi::canReview($user)) {
            Router::redirect('/projects/cesar-kpi/review');
            return;
        }

        http_response_code(403);
        echo 'KPI Tracker is not available for your account.';
    }

    // ─── Cesar's own record list ────────────────────────────────────────────────

    public function myRecords(): void
    {
        $user = Permission::requireLogin();
        if (!CesarKpi::canSubmit($user)) { http_response_code(403); echo 'Not authorized.'; return; }

        $filters = $this->filtersFromRequest();
        $records = CesarKpi::all($filters);

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

        require __DIR__ . '/../Views/cesar_kpi/my_records.php';
    }

    // ─── Entry form (new or edit draft) ────────────────────────────────────────

    public function entryForm(): void
    {
        $user = Permission::requireLogin();
        if (!CesarKpi::canSubmit($user)) { http_response_code(403); echo 'Not authorized.'; return; }

        $id    = (int)($_GET['id'] ?? 0);
        $entry = $id ? CesarKpi::find($id) : null;

        // Block editing locked/submitted/reviewed entries
        if ($entry && !in_array($entry['status'], ['draft', 'returned'])) {
            Router::redirect('/projects/cesar-kpi/view?id=' . $id);
            return;
        }

        $defaultWeek = ''; // No auto-fill — user must select dates manually
        $sites = CesarKpi::sites();

        require __DIR__ . '/../Views/cesar_kpi/entry_form.php';
    }

    // ─── Save draft ─────────────────────────────────────────────────────────────

    public function saveDraft(): void
    {
        $user = Permission::requireLogin();
        if (!CesarKpi::canSubmit($user)) { http_response_code(403); echo 'Not authorized.'; return; }

        $data       = $_POST;
        $thenSubmit = !empty($data['then_submit']);
        $isModal    = !empty($_GET['modal']);

        try {
            $id = CesarKpi::saveDraft($data);
        } catch (\Exception $e) {
            $_SESSION['cesar_kpi_flash'] = ['type' => 'error', 'msg' => $e->getMessage()];
            Router::redirect('/projects/cesar-kpi/my-records');
            return;
        }

        ActivityLog::log($user, 'cesar_kpi_draft_saved',
            'Saved draft Operations Manager KPI for week ending ' . ($data['week_ending'] ?? ''),
            null, null);

        if ($thenSubmit) {
            CesarKpi::submit($id, $user);
            ActivityLog::log($user, 'cesar_kpi_submitted',
                'Submitted Operations Manager KPI for week ending ' . ($data['week_ending'] ?? ''),
                null, null);
            // Notify Sara (all full-oversight managers) that Cesar has submitted for review
            self::notifyOversight($user,
                'César Saona submitted his Operations Manager KPI for review',
                '/projects/cesar-kpi/review');
            $_SESSION['cesar_kpi_flash'] = ['type' => 'success', 'msg' => 'Weekly KPI submitted for review.'];
            // In modal mode redirect to a page that posts message to parent
            Router::redirect($isModal
                ? '/projects/cesar-kpi/modal-done?msg=submitted'
                : '/projects/cesar-kpi/my-records');
            return;
        }

        $_SESSION['cesar_kpi_flash'] = ['type' => 'success', 'msg' => 'Draft saved.'];
        Router::redirect($isModal ? '/projects/cesar-kpi/modal-done?msg=saved' : '/projects/cesar-kpi/entry?id=' . $id);
    }

    // ─── Modal done: posts message to parent window then closes ─────────────────

    public function modalDone(): void
    {
        Permission::requireLogin();
        $msg = $_GET['msg'] ?? 'saved';
        $flash = $_SESSION['cesar_kpi_flash']['msg'] ?? '';
        unset($_SESSION['cesar_kpi_flash']);
        ?><!DOCTYPE html><html><head>
        <link rel="stylesheet" href="/assets/css/app.css?v=<?= defined('ASSET_VERSION') ? ASSET_VERSION : time() ?>">
        </head><body style="background:#fff;padding:40px 32px;font-family:inherit;">
        <div style="text-align:center;">
          <div style="font-size:32px;margin-bottom:12px;"><?= $msg==='submitted'?'✅':'💾' ?></div>
          <div style="font-size:16px;font-weight:700;color:var(--navy-900);margin-bottom:6px;">
            <?= $msg==='submitted' ? 'KPI Submitted!' : 'Draft Saved!' ?>
          </div>
          <?php if ($flash): ?>
          <div style="font-size:13px;color:var(--text-muted);"><?= htmlspecialchars($flash) ?></div>
          <?php endif; ?>
        </div>
        <script>
          // Notify parent to close modal and refresh
          try {
            window.parent.postMessage({type: 'kpi-<?= $msg === 'submitted' ? 'submitted' : 'saved' ?>'}, '*');
          } catch(e) {}
          // Fallback: redirect parent after short delay
          setTimeout(function() {
            try { window.parent.location.href = '/projects/cesar-kpi/my-records'; } catch(e) {}
          }, 800);
        </script>
        </body></html>
        <?php
    }

    // ─── Read-only view ─────────────────────────────────────────────────────────

    public function view(): void
    {
        $user = Permission::requireLogin();
        $id   = (int)($_GET['id'] ?? 0);
        $entry = CesarKpi::find($id);

        if (!$entry) { http_response_code(404); echo 'Not found.'; return; }

        $canSeeThis = CesarKpi::canSubmit($user) || CesarKpi::canReview($user);
        if (!$canSeeThis) { http_response_code(403); echo 'Not authorized.'; return; }

        $sites = CesarKpi::sites();
        require __DIR__ . '/../Views/cesar_kpi/view.php';
    }

    // ─── Review queue (Sara) ────────────────────────────────────────────────────

    public function reviewQueue(): void
    {
        $user = Permission::requireLogin();
        if (!CesarKpi::canReview($user)) { http_response_code(403); echo 'Not authorized.'; return; }

        $filters = $this->filtersFromRequest();
        $records = CesarKpi::all($filters);

        require __DIR__ . '/../Views/cesar_kpi/review_queue.php';
    }

    // ─── Review action (Sara) ───────────────────────────────────────────────────

    public function reviewAction(): void
    {
        $user = Permission::requireLogin();
        if (!CesarKpi::canReview($user)) { http_response_code(403); echo 'Not authorized.'; return; }

        $id    = (int)($_POST['id'] ?? 0);
        $entry = CesarKpi::find($id);
        if (!$entry) { http_response_code(404); echo 'Not found.'; return; }

        $action = $_POST['action'] ?? '';
        $week   = $entry['week_ending'];
        $kpiLink = '/projects/cesar-kpi/view?id=' . $id;

        // Cesar's manager account id (to push notifications back to him)
        $cesarManagerId = self::cesarManagerId();

        if ($action === 'approve') {
            $score   = (int)($_POST['review_score'] ?? 0);
            $comment = trim($_POST['review_comment_approve'] ?? '');
            CesarKpi::approve($id, $user, $score, $comment);
            $scoreNote = $score ? " Score: {$score}/10." : '';
            ActivityLog::log($user, 'cesar_kpi_approved',
                "Approved and locked César Saona's Operations Manager KPI (week ending {$week}).{$scoreNote}",
                null, null);
            // Notify Cesar
            if ($cesarManagerId) {
                \App\Models\Notification::push('manager', $cesarManagerId,
                    'Your KPI was approved' . ($score ? " — Score: {$score}/10" : ''),
                    'Week ending ' . $week . ($comment ? ': "' . mb_strimwidth($comment, 0, 120, '...') . '"' : ''),
                    $kpiLink);
            }
            $_SESSION['cesar_kpi_flash'] = ['type' => 'success', 'msg' => 'KPI approved and locked.'];
            // Also notify Sara/oversight so approvals are visible to her, not just submissions
            self::notifyOversight($user,
                "César Saona's Operations Manager KPI (week ending {$week}) approved.{$scoreNote}",
                $kpiLink);

        } elseif ($action === 'revise_score') {
            $newScore   = (int)($_POST['new_score'] ?? 0);
            $newComment = trim($_POST['new_comment'] ?? '');
            $reason     = trim($_POST['revise_reason'] ?? '');
            if (!$newScore || !$reason) {
                $_SESSION['cesar_kpi_flash'] = ['type' => 'error', 'msg' => 'New score and reason are required.'];
            } else {
                CesarKpi::reviseScore($id, $user, $newScore, $newComment, $reason);
                ActivityLog::log($user, 'cesar_kpi_score_revised',
                    "Revised score on César Saona's Operations Manager KPI (week ending {$week}) to {$newScore}/10. Reason: " . mb_strimwidth($reason, 0, 120, '...'),
                    null, null);
                // Notify Cesar
                if ($cesarManagerId) {
                    \App\Models\Notification::push('manager', $cesarManagerId,
                        'Your KPI score was revised to ' . $newScore . '/10',
                        'Week ending ' . $week . ($newComment ? ': "' . mb_strimwidth($newComment, 0, 120, '...') . '"' : ''),
                        $kpiLink);
                }
                $_SESSION['cesar_kpi_flash'] = ['type' => 'success', 'msg' => 'Score revised.'];
                self::notifyOversight($user,
                    "César Saona's Operations Manager KPI (week ending {$week}) score revised to {$newScore}/10.",
                    $kpiLink);
            }

        } elseif ($action === 'return') {
            $reason = trim($_POST['reason'] ?? '');
            CesarKpi::return_($id, $user, $reason);
            ActivityLog::log($user, 'cesar_kpi_returned',
                "Returned César Saona's Operations Manager KPI for edits (week ending {$week})" .
                ($reason ? ": \"{$reason}\"" : ''),
                null, null);
            // Notify Cesar
            if ($cesarManagerId) {
                \App\Models\Notification::push('manager', $cesarManagerId,
                    'Your KPI was returned for edits',
                    'Week ending ' . $week . ($reason ? ': "' . mb_strimwidth($reason, 0, 120, '...') . '"' : ''),
                    '/projects/cesar-kpi/entry?id=' . $id);
            }
            $_SESSION['cesar_kpi_flash'] = ['type' => 'success', 'msg' => 'KPI returned to César for edits.'];
            self::notifyOversight($user,
                "César Saona's Operations Manager KPI (week ending {$week}) returned for edits.",
                $kpiLink);

        } elseif ($action === 'comment') {
            $comment = trim($_POST['comment'] ?? '');
            CesarKpi::review($id, $user, $comment);
            ActivityLog::log($user, 'cesar_kpi_comment',
                "Commented on César Saona's Operations Manager KPI (week ending {$week})" .
                ($comment ? ": \"" . mb_strimwidth($comment, 0, 120, '...') . '"' : ''),
                null, null);
            // Notify Cesar
            if ($cesarManagerId) {
                \App\Models\Notification::push('manager', $cesarManagerId,
                    $user['name'] . ' commented on your KPI',
                    'Week ending ' . $week . ($comment ? ': "' . mb_strimwidth($comment, 0, 120, '...') . '"' : ''),
                    $kpiLink);
            }
        }

        Router::redirect('/projects/cesar-kpi/view?id=' . $id . (!empty($_POST['modal']) ? '&modal=1' : ''));
    }

    // ─── Helper ─────────────────────────────────────────────────────────────────

    private function filtersFromRequest(): array
    {
        return [
            'status' => $_GET['status'] ?? '',
            'from'   => $_GET['from']   ?? '',
            'to'     => $_GET['to']     ?? '',
        ];
    }

    /** Get Cesar's manager row id (used to push notifications to him). */
    private static function cesarManagerId(): ?int
    {
        try {
            $stmt = \App\Core\Database::connection()->prepare(
                "SELECT id FROM managers WHERE username = 'cesar.saona' LIMIT 1"
            );
            $stmt->execute();
            $row = $stmt->fetch();
            return $row ? (int)$row['id'] : null;
        } catch (\Throwable $e) {
            return null;
        }
    }

    /**
     * Push a notification to all full-oversight managers (Sara + super admins).
     * Skips the actor themselves so they don't get notified of their own action.
     */
    private static function notifyOversight(array $actor, string $title, string $link = ''): void
    {
        try {
            $db = \App\Core\Database::connection();
            $admins = $db->query("SELECT id FROM superadmins WHERE is_active = 1")->fetchAll(\PDO::FETCH_COLUMN);
            foreach ($admins as $adminId) {
                if ($actor['is_super_admin'] && (int)$adminId === $actor['user_id']) continue;
                \App\Models\Notification::push('superadmin', (int)$adminId, $title, '', $link);
            }
            $stmt = $db->prepare("SELECT id FROM managers WHERE username = 'sara.lasher' LIMIT 1");
            $stmt->execute();
            $row = $stmt->fetch();
            if ($row && (!($actor['user_type'] === 'manager') || (int)$row['id'] !== $actor['user_id'])) {
                \App\Models\Notification::push('manager', (int)$row['id'], $title, '', $link);
            }
        } catch (\Throwable $e) {}
    }
}
