<?php
/**
 * ProjectStarterController — per-project onboarding checklist.
 *
 *   /ProjectStarter/index/{project_id}   PM/PC view of the checklist for one project
 *   /ProjectStarter/myQueue              All OPEN starter tasks assigned to the current user
 *   /ProjectStarter/assignOwnerAj        POST task_id, user_id, user_name → set owner
 *   /ProjectStarter/completeAj           POST task_id, notes → DONE (seat tasks like ASSIGN_PC/ASSIGN_FS hydrate the matching c_projects column)
 *   /ProjectStarter/skipAj               POST task_id, reason → SKIPPED
 *   /ProjectStarter/reopenAj             POST task_id → OPEN
 */
class ProjectStarterController extends Controller
{
    public function indexAction($projectId = 0)
    {
        $projectId = (int)$projectId;
        $db = new DB();
        $rs = $db->mySelect(
            "SELECT c0d, project_no, project_name, project_type, project_customer,
                    project_manager_id, project_manager_name, pc_id, pc_name,
                    accountant_id, accountant_name, procurement_id, procurement_name,
                    fs_id, fs_name,
                    contract_value, currency, crm_status
               FROM c_projects WHERE c0d = :p AND deleted = 0",
            [':p' => $projectId]
        );
        if (empty($rs)) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">Project not found.</div>']);
            return;
        }
        $project = $rs[0];

        $ps    = new ProjectStarter();
        $tasks = $ps->tasksFor($projectId);

        // Candidate users per distinct owner_slot (for the reassign dropdowns)
        if (!class_exists('ApprovalChain')) require ROOT . '/app/models/ApprovalChain.php';
        $ac = new ApprovalChain();
        $slotOptions = [];
        foreach ($tasks as $t) {
            $slot = (string)$t['owner_slot'];
            if ($slot !== '' && !isset($slotOptions[$slot])) $slotOptions[$slot] = $ac->usersInSlot($slot);
        }

        $this->view->setLayout($this->roleLayout());
        $this->view->render('ProjectStarter/index', [
            'page_title'   => 'Onboard · ' . ($project['project_no'] ?? '') . ' · ' . ($project['project_name'] ?? ''),
            'project'      => $project,
            'tasks'        => $tasks,
            'slot_options' => $slotOptions,
        ]);
    }

    public function myQueueAction()
    {
        $ps  = new ProjectStarter();
        $uid = $this->currentUserId();
        // 8Y · filter + paginate onboarding queue.
        $filter = [
            'q'            => trim((string)($_GET['q']            ?? '')),
            'project_type' => (string)($_GET['type']              ?? ''),
            'customer_id'  => (int)   ($_GET['customer_id']       ?? 0),
        ];
        $pageSize = 25;
        $page     = max(1, (int)($_GET['page'] ?? 1));
        $total    = $ps->countOpenForUser($uid, $filter);
        $lastPage = max(1, (int)ceil($total / $pageSize));
        if ($page > $lastPage) $page = $lastPage;
        $tasks    = $ps->openForUserFiltered($uid, $filter + ['page' => $page, 'page_size' => $pageSize]);

        $this->view->setLayout($this->roleLayout());
        $this->view->render('ProjectStarter/myQueue', [
            'page_title' => 'My Onboarding Tasks',
            'tasks'      => $tasks,
            'filter'     => $filter,
            'page'       => $page,
            'page_size'  => $pageSize,
            'total'      => $total,
            'last_page'  => $lastPage,
            'customers'  => $ps->distinctCustomersInQueue($uid),
        ]);
    }

    public function assignOwnerAjAction()
    {
        try {
            $ps = new ProjectStarter();
            $ps->assignOwner(
                (int)($_POST['task_id']   ?? 0),
                (int)($_POST['user_id']   ?? 0),
                (string)($_POST['user_name'] ?? ''),
                $this->currentUserId()
            );
            $this->jsonResponse(['ok' => true, 'msg' => 'Owner assigned.']);
        } catch (\Throwable $e) {
            $this->jsonResponse(['ok' => false, 'msg' => $e->getMessage()]);
        }
    }

    public function completeAjAction()
    {
        try {
            (new ProjectStarter())->complete(
                (int)($_POST['task_id'] ?? 0),
                $this->currentUserId(),
                (string)($_SESSION['full_name'] ?? ''),
                (string)($_POST['notes'] ?? '')
            );
            $this->jsonResponse(['ok' => true, 'msg' => 'Task completed.']);
        } catch (\Throwable $e) {
            $this->jsonResponse(['ok' => false, 'msg' => $e->getMessage()]);
        }
    }

    public function skipAjAction()
    {
        try {
            (new ProjectStarter())->skip(
                (int)($_POST['task_id'] ?? 0),
                $this->currentUserId(),
                (string)($_SESSION['full_name'] ?? ''),
                (string)($_POST['reason'] ?? '')
            );
            $this->jsonResponse(['ok' => true, 'msg' => 'Task skipped.']);
        } catch (\Throwable $e) {
            $this->jsonResponse(['ok' => false, 'msg' => $e->getMessage()]);
        }
    }

    public function reopenAjAction()
    {
        try {
            (new ProjectStarter())->reopen((int)($_POST['task_id'] ?? 0), $this->currentUserId());
            $this->jsonResponse(['ok' => true, 'msg' => 'Task reopened.']);
        } catch (\Throwable $e) {
            $this->jsonResponse(['ok' => false, 'msg' => $e->getMessage()]);
        }
    }
}
