<?php
namespace App\Controllers;

use App\Core\Permission;
use App\Core\Router;
use App\Models\ActivityLog;
use App\Models\AccountsKpi;
use App\Models\Notification;

class JatinderKpiController
{
    private function isFullOversight(array $user): bool
    {
        return !empty($user['is_super_admin'])
            || ($user['user_type'] === 'manager' && ($user['username'] ?? '') === 'sara.lasher');
    }

    public function index(): void
    {
        $user = Permission::requireLogin();
        if (AccountsKpi::canSubmit($user))  { Router::redirect('/projects/jatinder-kpi/my-records'); return; }
        if (AccountsKpi::canReview($user))  { Router::redirect('/projects/jatinder-kpi/review'); return; }
        http_response_code(403); echo 'Not authorized.';
    }

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

        $filters = ['status'=>$_GET['status']??'','from'=>$_GET['from']??'','to'=>$_GET['to']??''];
        $records = AccountsKpi::forSubmitter($user['user_id'], $filters);
        $flash   = $_SESSION['jat_kpi_flash'] ?? null;
        unset($_SESSION['jat_kpi_flash']);
        require __DIR__ . '/../Views/jatinder_kpi/my_records.php';
    }

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

        $id    = (int)($_GET['id'] ?? 0);
        $entry = $id ? AccountsKpi::find($id) : null;
        if ($entry && (int)$entry['submitter_id'] !== $user['user_id']) {
            http_response_code(403); echo 'Not authorized.'; return;
        }
        $defaultWeekEnding = '';
        // Load employee names for Site Improvement dropdown
        try {
            $db = \App\Core\Database::connection();
            $allPeopleNames = $db->query("SELECT name FROM employees WHERE name IS NOT NULL ORDER BY name")
                ->fetchAll(\PDO::FETCH_COLUMN);
            $allPeopleNames = array_values(array_unique($allPeopleNames));
        } catch (\Throwable $e) {
            $allPeopleNames = [];
        }
        require __DIR__ . '/../Views/jatinder_kpi/entry_form.php';
    }

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

        $isModal    = !empty($_GET['modal']) || !empty($_POST['modal']);
        $weekEnding = trim($_POST['week_ending'] ?? date('Y-m-d'));
        $existingId = (int)($_POST['entry_id'] ?? 0) ?: null;

        try {
            $id = AccountsKpi::saveDraft($user, $weekEnding, $_POST, $existingId);
        } catch (\Exception $e) {
            $_SESSION['jat_kpi_flash'] = ['type'=>'error','msg'=>$e->getMessage()];
            Router::redirect('/projects/jatinder-kpi/my-records');
            return;
        }

        ActivityLog::log($user, 'jatinder_kpi_draft_saved',
            'Saved draft Jatinder KPI for week ending ' . $weekEnding);

        if (!empty($_POST['then_submit'])) {
            AccountsKpi::submit($id, $user);
            ActivityLog::log($user, 'jatinder_kpi_submitted',
                'Submitted Jatinder KPI for week ending ' . $weekEnding . ' for review');
            // Notify Cesar (direct supervisor)
            self::notifyCesar($user['name'] . ' submitted a weekly KPI for review',
                '/projects/jatinder-kpi/review');
            $_SESSION['jat_kpi_flash'] = ['type'=>'success','msg'=>'KPI submitted for review.'];
            Router::redirect($isModal ? '/projects/jatinder-kpi/modal-done?msg=submitted'
                                      : '/projects/jatinder-kpi/my-records');
            return;
        }

        $_SESSION['jat_kpi_flash'] = ['type'=>'success','msg'=>'Draft saved.'];
        // In modal mode: close modal and reload records (don't reopen draft)
        Router::redirect($isModal ? '/projects/jatinder-kpi/modal-done?msg=saved'
                                  : '/projects/jatinder-kpi/entry?id=' . $id);
    }

    public function modalDone(): void
    {
        Permission::requireLogin();
        $msg  = $_GET['msg'] ?? 'saved';
        $flash = $_SESSION['jat_kpi_flash']['msg'] ?? ($msg === 'submitted' ? 'KPI submitted for review.' : 'Draft saved.');
        require __DIR__ . '/../Views/jatinder_kpi/modal_done.php';
    }

    public function view(): void
    {
        $user = Permission::requireLogin();
        $id   = (int)($_GET['id'] ?? 0);
        $entry = AccountsKpi::find($id);
        if (!$entry) { http_response_code(404); echo 'Not found.'; return; }

        $isSubmitter = AccountsKpi::canSubmit($user) && (int)$entry['submitter_id'] === $user['user_id'];
        $isReviewer  = AccountsKpi::canReview($user);
        if (!$isSubmitter && !$isReviewer) { http_response_code(403); echo 'Not authorized.'; return; }

        $reviewHistory = AccountsKpi::reviewHistory($id);
        $isModalMode   = !empty($_GET['modal']);
        require __DIR__ . '/../Views/jatinder_kpi/view.php';
    }

    /**
     * Append a response to an Accounts KPI's review discussion.
     *
     * Only the record's own submitter (Jatinder) may post; reviewers
     * (Cesar / Sara) are view-only, matching the Scheduling KPI behaviour.
     *
     * Strictly conversational: never touches kpi_accounts_entries — no
     * status, score, comment or lock-state change.
     */
    public function postReply(): void
    {
        $user  = Permission::requireLogin();
        $id    = (int)($_POST['id'] ?? 0);
        $entry = AccountsKpi::find($id);
        if (!$entry) { http_response_code(404); echo 'Not found.'; return; }

        $isSubmitter = AccountsKpi::canSubmit($user) && (int)$entry['submitter_id'] === $user['user_id'];
        $isReviewer  = AccountsKpi::canReview($user);

        // Same view rule as view(); posting is narrower — owner only.
        if (!$isSubmitter && !$isReviewer) { http_response_code(403); echo 'Not authorized.'; return; }
        if (!$isSubmitter) { http_response_code(403); echo 'Only the owner of this KPI record can post a response.'; return; }

        $isModal = !empty($_POST['modal']);
        $kpiLink = '/projects/jatinder-kpi/view?id=' . $id;
        $body    = trim($_POST['reply_body'] ?? '');

        if ($body === '') {
            $_SESSION['jat_kpi_flash'] = ['type'=>'error','msg'=>'Please write a response before saving.'];
            Router::redirect($kpiLink . ($isModal ? '&modal=1' : ''));
            return;
        }

        $msgId = \App\Models\KpiDiscussion::add($id, $user, 'submitter', $body, 'accounts');
        if (!$msgId) {
            $_SESSION['jat_kpi_flash'] = ['type'=>'error','msg'=>'Sorry — your response could not be saved. Please try again.'];
            Router::redirect($kpiLink . ($isModal ? '&modal=1' : ''));
            return;
        }

        $week    = $entry['week_ending'];
        $snippet = mb_strimwidth($body, 0, 120, '...');

        ActivityLog::log($user, 'jatinder_kpi_reply_added',
            'Responded to the review on their Accounts KPI (week ending ' . $week . '): "' . $snippet . '"');

        // Notify the reviewer who left the comment; fall back to Cesar.
        $notified = false;
        if (!empty($entry['reviewer_id']) && !empty($entry['reviewer_type'])) {
            Notification::push($entry['reviewer_type'], (int)$entry['reviewer_id'],
                $user['name'] . ' responded to your KPI review',
                'Week ending ' . $week . ': "' . $snippet . '"', $kpiLink);
            $notified = true;
        }
        if (!$notified) {
            $cesarId = self::cesarManagerId();
            if ($cesarId) {
                Notification::push('manager', $cesarId,
                    $user['name'] . ' responded to your KPI review',
                    'Week ending ' . $week . ': "' . $snippet . '"', $kpiLink);
            }
        }
        // Sara keeps full oversight of the conversation.
        self::notifySara($user['name'] . ' responded on their Accounts KPI (week ending ' . $week . ').', $kpiLink);

        $_SESSION['jat_kpi_flash'] = ['type'=>'success','msg'=>'Your response has been saved.'];
        Router::redirect($kpiLink . ($isModal ? '&modal=1' : ''));
    }

    /** Cesar's manager id — the default reviewer for Accounts KPIs. */
    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;
        }
    }

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

        $filters = ['status'=>$_GET['status']??'','from'=>$_GET['from']??'','to'=>$_GET['to']??''];
        $records = AccountsKpi::allEntries($filters);
        require __DIR__ . '/../Views/jatinder_kpi/review_queue.php';
    }

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

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

        $action  = $_POST['action'] ?? '';
        $week    = $entry['week_ending'];
        $kpiLink = '/projects/jatinder-kpi/view?id=' . $id;
        $jatId   = self::jatinderManagerId();

        if ($action === 'approve') {
            $score   = (int)($_POST['review_score'] ?? 0);
            $comment = trim($_POST['review_comment_approve'] ?? '');
            AccountsKpi::approve($id, $user, $score, $comment);
            $scoreNote = $score ? " Score: {$score}/10." : '';
            ActivityLog::log($user, 'jatinder_kpi_approved',
                "Approved Jatinder Kumar's KPI (week ending {$week}).{$scoreNote}");
            if ($jatId) {
                Notification::push('manager', $jatId,
                    'Your KPI was approved' . ($score ? " — Score: {$score}/10" : ''),
                    'Week ending ' . $week . ($comment ? ': "' . mb_strimwidth($comment,0,120,'...') . '"' : ''),
                    $kpiLink);
            }
            self::notifySara("Jatinder's KPI (week ending {$week}) approved.{$scoreNote}", $kpiLink);
            $_SESSION['jat_kpi_flash'] = ['type'=>'success','msg'=>'KPI approved and locked.'];

        } elseif ($action === 'return') {
            $reason = trim($_POST['reason'] ?? trim($_POST['return_reason'] ?? ''));
            if (!$reason) {
                $_SESSION['jat_kpi_flash'] = ['type'=>'error','msg'=>'A return reason is required.'];
                Router::redirect($kpiLink); return;
            }
            AccountsKpi::return_($id, $user, $reason);
            ActivityLog::log($user, 'jatinder_kpi_returned',
                "Returned Jatinder Kumar's KPI for edits (week ending {$week}): \"{$reason}\"");
            if ($jatId) {
                Notification::push('manager', $jatId,
                    'Your KPI was returned for edits',
                    'Week ending ' . $week . ': "' . mb_strimwidth($reason,0,120,'...') . '"',
                    '/projects/jatinder-kpi/entry?id=' . $id);
            }
            $_SESSION['jat_kpi_flash'] = ['type'=>'success','msg'=>'KPI returned for edits.'];
            self::notifySara("Jatinder's KPI (week ending {$week}) returned for edits.", $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['jat_kpi_flash'] = ['type'=>'error','msg'=>'New score and reason are required.'];
            } else {
                AccountsKpi::reviseScore($id, $user, $newScore, $newComment, $reason);
                ActivityLog::log($user, 'jatinder_kpi_score_revised',
                    "Revised score on Jatinder Kumar's KPI (week ending {$week}) to {$newScore}/10.");
                if ($jatId) {
                    Notification::push('manager', $jatId,
                        'Your KPI score was revised to ' . $newScore . '/10',
                        'Week ending ' . $week,
                        $kpiLink);
                }
                $_SESSION['jat_kpi_flash'] = ['type'=>'success','msg'=>'Score revised.'];
                self::notifySara("Jatinder's KPI (week ending {$week}) score revised to {$newScore}/10.", $kpiLink);
            }
        }

        Router::redirect($kpiLink . (!empty($_POST['modal']) ? '&modal=1' : ''));
    }

    // ── Helpers ──────────────────────────────────────────────────────────────

    private static function jatinderManagerId(): ?int
    {
        try {
            $stmt = \App\Core\Database::connection()->prepare(
                "SELECT id FROM managers WHERE username='jatinder.kumar' LIMIT 1"
            );
            $stmt->execute();
            $row = $stmt->fetch();
            return $row ? (int)$row['id'] : null;
        } catch (\Throwable $e) { return null; }
    }

    private static function notifyCesar(string $title, string $link = ''): void
    {
        try {
            $db   = \App\Core\Database::connection();
            $stmt = $db->prepare("SELECT id FROM managers WHERE username='cesar.saona' LIMIT 1");
            $stmt->execute();
            $row  = $stmt->fetch();
            if ($row) Notification::push('manager', (int)$row['id'], $title, '', $link);
        } catch (\Throwable $e) {}
    }

    private static function notifySara(string $title, string $link = ''): void
    {
        try {
            $db   = \App\Core\Database::connection();
            // Super admins
            $admins = $db->query("SELECT id FROM superadmins")->fetchAll(\PDO::FETCH_COLUMN);
            foreach ($admins as $aid) Notification::push('superadmin', (int)$aid, $title, '', $link);
            // sara.lasher manager account
            $stmt = $db->prepare("SELECT id FROM managers WHERE username='sara.lasher' LIMIT 1");
            $stmt->execute();
            $row = $stmt->fetch();
            if ($row) Notification::push('manager', (int)$row['id'], $title, '', $link);
        } catch (\Throwable $e) {}
    }
}
