<?php
/**
 * WorksCustomerRetentionController — customer-side retention pool viewer + record-release.
 *
 *   /WorksCustomerRetention/pool/{project_id}   — pool summary + IPC breakdown + release log
 *   /WorksCustomerRetention/recordReleaseAj     — POST project_id + amount + released_on + notes + matched_receipt_id
 *   /WorksCustomerRetention/deleteReleaseAj     — POST release_id (soft-delete a mis-entry)
 */
class WorksCustomerRetentionController 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">Customer retention is available on <strong>works</strong> projects only.</div>']);
            return;
        }
        if (!class_exists('WorksCustomerRetention')) require_once ROOT . '/app/models/WorksCustomerRetention.php';
        $wcr = new WorksCustomerRetention();

        $this->view->setLayout($this->roleLayout());
        $this->view->render('WorksCustomerRetention/pool', [
            'page_title' => 'Customer retention · ' . ($prj[0]['project_no'] ?? ''),
            'project'    => $prj[0],
            'pool'       => $wcr->poolFor($projectId),
            'holdings'   => $wcr->holdingsBreakdown($projectId),
            'releases'   => $wcr->releasesFor($projectId),
        ]);
    }

    public function recordReleaseAjAction()
    {
        header('Content-Type: application/json');
        try {
            $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 record a release.']); return;
            }
            if (!class_exists('WorksCustomerRetention')) require_once ROOT . '/app/models/WorksCustomerRetention.php';
            $res = (new WorksCustomerRetention())->recordRelease(
                (int)($_POST['project_id']         ?? 0),
                (float)($_POST['amount']           ?? 0),
                (string)($_POST['released_on']     ?? date('Y-m-d')),
                (string)($_POST['notes']           ?? ''),
                (int)($_POST['matched_receipt_id'] ?? 0),
                (int)($_SESSION['user_id']         ?? 0),
                (string)($_SESSION['full_name']    ?? '')
            );
            echo json_encode($res);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function deleteReleaseAjAction()
    {
        header('Content-Type: application/json');
        try {
            $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 remove a release.']); return;
            }
            if (!class_exists('WorksCustomerRetention')) require_once ROOT . '/app/models/WorksCustomerRetention.php';
            $res = (new WorksCustomerRetention())->deleteRelease(
                (int)($_POST['release_id'] ?? 0),
                (int)($_SESSION['user_id'] ?? 0)
            );
            echo json_encode($res);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }
}
