<?php
class OnboardingController extends Controller
{
    /** Inbox: projects in NOT_STARTED / IN_PROGRESS / SUBMITTED. */
    public function indexAction()
    {
        $db = new DB();
        $rows = $db->mySelect(
            "SELECT p.c0d, p.project_no, p.project_name, p.project_type, p.project_customer,
                    p.origin, p.crm_status, p.migrated_flag, p.contract_value, p.currency,
                    o.c0d AS onb_id,
                    (SELECT COUNT(*) FROM crm_project_checklist_items ck WHERE ck.project_id = p.c0d) AS ck_total,
                    (SELECT COUNT(*) FROM crm_project_checklist_items ck WHERE ck.project_id = p.c0d AND ck.is_complete = 1) AS ck_done,
                    (SELECT a.c0d FROM fin_approvals a
                       WHERE a.entity_type = 'crm_project_onboarding' AND a.entity_id = o.c0d
                             AND a.status = 'IN_PROGRESS' AND a.deleted = 0
                       ORDER BY a.c0d DESC LIMIT 1) AS approval_id
               FROM c_projects p
          LEFT JOIN crm_project_onboarding o ON o.project_id = p.c0d AND o.deleted = 0
              WHERE p.deleted = 0
                AND p.crm_status IN ('NOT_STARTED', 'IN_PROGRESS', 'SUBMITTED')
              ORDER BY p.c0d DESC",
            []
        ) ?: [];
        $this->view->setLayout($this->roleLayout());
        $this->view->render('Onboarding/index', [
            'page_title' => 'CRM Onboarding',
            'rows'       => $rows,
        ]);
    }

    /** AJAX: toggle a checklist item. */
    public function toggleAjAction()
    {
        $iid  = (int)($_POST['item_id'] ?? 0);
        $done = (int)($_POST['is_complete'] ?? 0) === 1 ? 1 : 0;
        if ($iid <= 0) { $this->jsonResponse(['ok' => false, 'msg' => 'item_id required']); return; }
        $db  = new DB();
        $uid = $this->currentUserId();
        $r = $db->insertUpdate(
            "UPDATE crm_project_checklist_items
                SET is_complete = :d, completed_on = IF(:d=1, NOW(), NULL), completed_by = IF(:d=1, :uid, 0)
              WHERE c0d = :id",
            [':d' => $done, ':uid' => $uid, ':id' => $iid]
        );
        // Bump the project's crm_status to IN_PROGRESS if it was NOT_STARTED
        $ck = $db->mySelect("SELECT project_id FROM crm_project_checklist_items WHERE c0d = :id", [':id' => $iid]);
        if (!empty($ck)) {
            $pid = (int)$ck[0]['project_id'];
            $db->insertUpdate(
                "UPDATE c_projects SET crm_status = 'IN_PROGRESS', edited_by = :uid
                  WHERE c0d = :pid AND crm_status = 'NOT_STARTED'",
                [':uid' => $uid, ':pid' => $pid]
            );
        }
        $this->jsonResponse(['ok' => $r['success'] >= 0, 'msg' => 'Saved.']);
    }

    /**
     * Slice 8S-9 · AJAX: manual sync of the Services checklist for a project.
     * Called by the CRM "Refresh checks" button on the onboarding page.
     * Returns {ok, evaluated, flipped_on:[], flipped_off:[]}.
     */
    public function syncServicesChecklistAjAction()
    {
        $pid = (int)($_POST['project_id'] ?? 0);
        if ($pid <= 0) { $this->jsonResponse(['ok' => false, 'msg' => 'project_id required']); return; }
        try {
            if (!class_exists('Projects')) require_once ROOT . '/app/models/Projects.php';
            $res = (new Projects())->syncServicesChecklist($pid);
            $this->jsonResponse(array_merge(['ok' => true], $res));
        } catch (\Throwable $e) {
            $this->jsonResponse(['ok' => false, 'msg' => $e->getMessage()]);
        }
    }

    /** AJAX: submit the project's onboarding for chain CRM_PROJECT_ONBOARDING. */
    public function submitAjAction()
    {
        $pid = (int)($_POST['project_id'] ?? 0);
        if ($pid <= 0) { $this->jsonResponse(['ok' => false, 'msg' => 'project_id required']); return; }

        $db = new DB();
        $p  = $db->mySelect(
            "SELECT p.c0d, p.project_no, p.project_name, p.crm_status, p.migrated_flag,
                    o.c0d AS onb_id
               FROM c_projects p
          LEFT JOIN crm_project_onboarding o ON o.project_id = p.c0d
              WHERE p.c0d = :id AND p.deleted = 0 LIMIT 1",
            [':id' => $pid]
        );
        $row = $p[0] ?? null;
        if (!$row) { $this->jsonResponse(['ok' => false, 'msg' => 'Project not found.']); return; }
        if ((int)$row['migrated_flag'] === 1) { $this->jsonResponse(['ok' => false, 'msg' => 'Migrated projects do not use the chain.']); return; }
        if (in_array($row['crm_status'], ['SUBMITTED','APPROVED'], true)) {
            $this->jsonResponse(['ok' => false, 'msg' => 'Already submitted or approved.']); return;
        }
        // Slice 8S-9 · Auto-tick data-gated items before checking completeness so CRM can't
        // submit a stale checklist that no longer matches the contract data.
        try {
            if (!class_exists('Projects')) require_once ROOT . '/app/models/Projects.php';
            (new Projects())->syncServicesChecklist($pid);
        } catch (\Throwable $e) { /* best-effort */ }
        $ck = $db->mySelect(
            "SELECT COUNT(*) AS tot, SUM(is_complete) AS done FROM crm_project_checklist_items WHERE project_id = :id",
            [':id' => $pid]
        );
        $tot  = (int)($ck[0]['tot'] ?? 0);
        $done = (int)($ck[0]['done'] ?? 0);
        if ($tot === 0 || $done < $tot) {
            $this->jsonResponse(['ok' => false, 'msg' => 'All checklist items must be complete before submission.']);
            return;
        }
        if (!$row['onb_id']) {
            // Race safety: ensure the onboarding row exists
            $db->insertUpdate(
                "INSERT INTO crm_project_onboarding (project_id, created_by, edited_by) VALUES (:pid, :uid, :uid)",
                [':pid' => $pid, ':uid' => $this->currentUserId()]
            );
            $onbIdRow = $db->mySelect("SELECT c0d FROM crm_project_onboarding WHERE project_id = :pid", [':pid' => $pid]);
            $onbId = (int)($onbIdRow[0]['c0d'] ?? 0);
        } else {
            $onbId = (int)$row['onb_id'];
        }

        $ac = new ApprovalChain();
        $res = $ac->submit([
            'chain_key'    => 'CRM_PROJECT_ONBOARDING',
            'entity_type'  => 'crm_project_onboarding',
            'entity_id'    => $onbId,
            'ref_label'    => $row['project_no'] . ' · ' . $row['project_name'],
            'return_url'   => 'Projects/view/' . $pid,
            'user_id'      => $this->currentUserId(),
            'user_name'    => $_SESSION['full_name'] ?? '',
            'user_group'   => $_SESSION['user_group_name'] ?? '',
            'comment'      => 'Submitted for CRM onboarding approval',
        ]);
        if ($res['ok']) {
            $db->insertUpdate(
                "UPDATE c_projects SET crm_status = 'SUBMITTED', edited_by = :uid WHERE c0d = :pid",
                [':uid' => $this->currentUserId(), ':pid' => $pid]
            );
            $db->insertUpdate(
                "UPDATE crm_project_onboarding SET submitted_at = NOW(), submitted_by = :uid WHERE c0d = :id",
                [':uid' => $this->currentUserId(), ':id' => $onbId]
            );
        }
        $this->jsonResponse($res);
    }
}
