<?php

namespace App\Controllers;

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

class WorkspaceController
{
    public function home(): void
    {
        $user = Permission::requireLogin();

        $departments = $user['is_super_admin']
            ? Lookup::departments()
            : Lookup::departmentsForUser($user['user_type'], $user['user_id']);

        $projects = $user['is_super_admin']
            ? Lookup::allProjects()
            : Lookup::allProjectsForUser($user['user_type'], $user['user_id']);

        $db = Database::connection();
        $stmt = $db->prepare("SELECT * FROM notifications WHERE user_type = :t AND user_id = :id ORDER BY created_at DESC LIMIT 8");
        $stmt->execute(['t' => $user['user_type'], 'id' => $user['user_id']]);
        $notifications = $stmt->fetchAll();

        $recentActivity = \App\Models\ActivityLog::visibleTo($user, 8);

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

    public function department(): void
    {
        $user = Permission::requireLogin();
        $deptId = (int)($_GET['id'] ?? 0);

        $db = Database::connection();
        $stmt = $db->prepare("SELECT * FROM departments WHERE id = :id");
        $stmt->execute(['id' => $deptId]);
        $department = $stmt->fetch();

        if (!$department) {
            http_response_code(404);
            echo 'Department not found.';
            return;
        }

        // Access check - Super Admin sees everything, others must be assigned
        if (!$user['is_super_admin']) {
            $check = $db->prepare("SELECT 1 FROM user_departments WHERE user_type=:t AND user_id=:id AND department_id=:d");
            $check->execute(['t' => $user['user_type'], 'id' => $user['user_id'], 'd' => $deptId]);
            if (!$check->fetch()) {
                http_response_code(403);
                echo 'You do not have access to this department.';
                return;
            }
        }

        $projects = Lookup::projectsForUserInDepartment($user['user_type'], $user['user_id'], $deptId);

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

    public function project(): void
    {
        $user = Permission::requireLogin();
        $projectId = (int)($_GET['id'] ?? 0);

        $db = Database::connection();
        $stmt = $db->prepare("SELECT p.*, d.name AS department_name, d.id AS department_id FROM projects p JOIN departments d ON d.id = p.department_id WHERE p.id = :id");
        $stmt->execute(['id' => $projectId]);
        $project = $stmt->fetch();

        if (!$project) {
            http_response_code(404);
            echo 'Project not found.';
            return;
        }

        if (!$user['is_super_admin']) {
            $check = $db->prepare("SELECT 1 FROM user_projects WHERE user_type=:t AND user_id=:id AND project_id=:p");
            $check->execute(['t' => $user['user_type'], 'id' => $user['user_id'], 'p' => $projectId]);
            if (!$check->fetch()) {
                http_response_code(403);
                echo 'You do not have access to this project.';
                return;
            }
        }

        $stmt = $db->prepare("SELECT * FROM dashboard_widgets WHERE project_id = :p AND is_active = 1 ORDER BY sort_order");
        $stmt->execute(['p' => $projectId]);
        $widgets = $stmt->fetchAll();

        // For super admin on the KPI/Scheduling project, load dashboard data and render inline
        $deptName   = strtolower(trim($project['department_name'] ?? ''));
        $projCode   = strtolower(trim($project['code'] ?? ''));
        $projName   = strtolower(trim($project['name'] ?? ''));
        $isDeptKpi  = $deptName === 'scheduling'
                   || $projCode === 'kpi'
                   || $projCode === 'scheduling_operations'
                   || $projName === 'kpi';

        // Show company dashboard for: super admin OR sara.lasher (top-level manager/CEO equivalent)
        // sara.lasher is a manager account that has full KPI oversight like a super admin
        $canSeeDashboard = $user['is_super_admin']
            || ($user['user_type'] === 'manager' && ($user['username'] ?? '') === 'sara.lasher');

        if ($canSeeDashboard && $isDeptKpi) {
            // Load all data the company dashboard needs
            $schedulingDeptId = KpiScheduling::departmentIdFor('scheduling') ?? 0;
            $activeDeptId = $schedulingDeptId;
            $filters = [
                'status'    => $_GET['status']    ?? '',
                'employee'  => $_GET['employee']  ?? '',
                'range'     => $_GET['range']     ?? '',
                'from_date' => $_GET['from_date'] ?? '',
                'to_date'   => $_GET['to_date']   ?? '',
            ];
            $records     = KpiScheduling::allEntries($filters);
            $departments = Lookup::departments();
            $submitters = [];
            try {
                $stmt2 = $db->prepare(
                    "SELECT DISTINCT m.id, m.name FROM managers m
                     JOIN kpi_scheduling_entries k ON k.submitter_id = m.id
                     ORDER BY m.name"
                );
                $stmt2->execute();
                $submitters = $stmt2->fetchAll();
            } catch (\Throwable $e) {}
            $admin = $user;
            require __DIR__ . '/../Views/kpi/company_dashboard.php';
            return;
        }

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