<?php
/**
 * WorksRetentionController — retention pool + release surface per project.
 *
 *   /WorksRetention/pool/{project_id}   — pool summary + holdings table
 *   /WorksRetention/releaseAj           — POST holding_id + notes + [force=1]
 *   /WorksRetention/setTermsAj          — POST project_id + pct + dlp_days (Admin/FM)
 */
class WorksRetentionController extends Controller
{
    public function poolAction($projectId = 0)
    {
        $projectId = (int)$projectId;
        $db = new DB();
        $prj = $db->mySelect(
            "SELECT c0d, project_no, project_name, project_customer, project_type, currency
               FROM c_projects WHERE c0d = :p AND deleted = 0",
            [':p' => $projectId]
        );
        if (empty($prj)) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">Project not found.</div>']);
            return;
        }
        if (($prj[0]['project_type'] ?? '') !== 'works') {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-warning">Retention pool is available on <strong>works</strong> projects only.</div>']);
            return;
        }
        if (!class_exists('WorksRetention')) require_once ROOT . '/app/models/WorksRetention.php';
        $wr = new WorksRetention();

        $this->view->setLayout($this->roleLayout());
        $this->view->render('WorksRetention/pool', [
            'page_title' => 'Retention pool · ' . ($prj[0]['project_no'] ?? ''),
            'project'    => $prj[0],
            'terms'      => $wr->termsFor($projectId) ?: ['pct' => 0.0, 'dlp_days' => 365],
            'pool'       => $wr->poolFor($projectId),
            'holdings'   => $wr->holdingsFor($projectId),
        ]);
    }

    /** POST holding_id + notes + [force=1] → release a HELD row. */
    public function releaseAjAction()
    {
        header('Content-Type: application/json');
        try {
            if (!class_exists('WorksRetention')) require_once ROOT . '/app/models/WorksRetention.php';
            $group = strtoupper((string)($_SESSION['user_group_name'] ?? ''));
            // Only FM / Administrator may release; PC/PM can eyeball the pool only.
            if (!in_array($group, ['FINANCE MANAGER','ADMINISTRATOR'], true)) {
                echo json_encode(['ok' => false, 'msg' => 'Only Finance Manager / Administrator can release retention.']); return;
            }
            $res = (new WorksRetention())->release(
                (int)($_POST['holding_id'] ?? 0),
                (int)($_SESSION['user_id']  ?? 0),
                (string)($_SESSION['full_name'] ?? ''),
                (string)($_POST['notes'] ?? ''),
                !empty($_POST['force'])
            );
            echo json_encode($res);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    /** POST project_id + pct + dlp_days → update the BOQ header (Admin/FM only). */
    public function setTermsAjAction()
    {
        header('Content-Type: application/json');
        try {
            if (!class_exists('WorksRetention')) require_once ROOT . '/app/models/WorksRetention.php';
            $group = strtoupper((string)($_SESSION['user_group_name'] ?? ''));
            if (!in_array($group, ['FINANCE MANAGER','ADMINISTRATOR'], true)) {
                echo json_encode(['ok' => false, 'msg' => 'Only Finance Manager / Administrator can set retention terms.']); return;
            }
            $res = (new WorksRetention())->setTerms(
                (int)($_POST['project_id'] ?? 0),
                (float)($_POST['pct']       ?? 0),
                (int)($_POST['dlp_days']    ?? 365)
            );
            echo json_encode($res);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }
}
