<?php
/**
 * WorkInstancesController — assignee & reviewer surface for live template instances.
 *
 *   /WorkInstances/myQueue        my assigned instances
 *   /WorkInstances/view/{id}      wizard-style checklist detail
 *   /WorkInstances/createAj       POST template_id + target → new DRAFT instance
 *   /WorkInstances/claimAj        POST id
 *   /WorkInstances/reassignAj     POST id, user_id, user_name
 *   /WorkInstances/saveResultAj   POST instance_id, item_id, value, note
 *   /WorkInstances/submitAj       POST id
 *   /WorkInstances/approveAj      POST id, notes
 *   /WorkInstances/rejectAj       POST id, reason
 *   /WorkInstances/reopenAj       POST id
 *   /WorkInstances/cancelAj       POST id, reason
 */
class WorkInstancesController extends Controller
{
    public function myQueueAction()
    {
        $rows = (new WorkInstances())->myQueue($this->currentUserId(), (string)($_GET['status'] ?? ''));
        $this->view->setLayout($this->roleLayout());
        $this->view->render('WorkInstances/myQueue', [
            'page_title' => 'My Work Queue',
            'rows'       => $rows,
            'status'     => (string)($_GET['status'] ?? ''),
        ]);
    }

    public function viewAction($id = 0)
    {
        $wi = new WorkInstances();
        $inst = $wi->findById((int)$id);
        if (!$inst) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">Instance not found.</div>']);
            return;
        }
        if (!class_exists('WorkTemplates')) require_once ROOT . '/app/models/WorkTemplates.php';
        $items   = (new WorkTemplates())->itemsForTemplate((int)$inst['template_id']);
        $results = $wi->resultsMap((int)$id);

        $group   = strtoupper((string)($_SESSION['user_group_name'] ?? ''));
        $isAssignee = (int)$inst['assignee_id'] === $this->currentUserId();
        $isReviewer = in_array($group, ['ADMINISTRATOR','EXECUTIVE','PROJECT MANAGER','FINANCE MANAGER'], true)
                      || strtoupper((string)$inst['reviewed_by_name']) !== ''; // reviewer previously
        // Actions
        $canSave    = in_array($inst['status'], ['DRAFT','REJECTED'], true) && ($isAssignee || (int)$inst['assignee_id'] === 0);
        $canSubmit  = in_array($inst['status'], ['DRAFT','REJECTED'], true) && ($isAssignee || (int)$inst['assignee_id'] === 0);
        $canReview  = $inst['status'] === 'SUBMITTED' && $isReviewer;
        $canReopen  = $inst['status'] === 'REJECTED' && $isAssignee;
        $canClaim   = $inst['status'] === 'DRAFT' && (int)$inst['assignee_id'] === 0;

        $this->view->setLayout($this->roleLayout());
        $this->view->render('WorkInstances/view', [
            'page_title' => $inst['ref_label'] ?: ($inst['template_title'] . ' · #' . $inst['c0d']),
            'inst'       => $inst,
            'items'      => $items,
            'results'    => $results,
            'can_save'   => $canSave,
            'can_submit' => $canSubmit,
            'can_review' => $canReview,
            'can_reopen' => $canReopen,
            'can_claim'  => $canClaim,
        ]);
    }

    public function createAjAction()
    {
        header('Content-Type: application/json');
        try {
            $id = (new WorkInstances())->create(
                (int)($_POST['template_id'] ?? 0),
                (string)($_POST['target_entity_type'] ?? 'c_projects'),
                (int)($_POST['target_entity_id'] ?? 0),
                $_POST,
                (int)($_SESSION['user_id'] ?? 0),
                (string)($_SESSION['full_name'] ?? '')
            );
            echo json_encode(['ok' => true, 'id' => $id]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function claimAjAction()
    {
        header('Content-Type: application/json');
        try {
            (new WorkInstances())->claim(
                (int)($_POST['id'] ?? 0),
                (int)($_SESSION['user_id'] ?? 0),
                (string)($_SESSION['full_name'] ?? '')
            );
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function reassignAjAction()
    {
        header('Content-Type: application/json');
        try {
            (new WorkInstances())->reassign(
                (int)($_POST['id'] ?? 0),
                (int)($_POST['user_id'] ?? 0),
                (string)($_POST['user_name'] ?? ''),
                (int)($_SESSION['user_id'] ?? 0)
            );
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function saveResultAjAction()
    {
        header('Content-Type: application/json');
        try {
            (new WorkInstances())->setResult(
                (int)($_POST['instance_id'] ?? 0),
                (int)($_POST['item_id'] ?? 0),
                [
                    'value'       => $_POST['value']       ?? '',
                    'note'        => (string)($_POST['note'] ?? ''),
                    'time_source' => (string)($_POST['time_source'] ?? 'SERVER'),
                ],
                (int)($_SESSION['user_id'] ?? 0)
            );
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function submitAjAction()
    {
        header('Content-Type: application/json');
        try {
            (new WorkInstances())->submit(
                (int)($_POST['id'] ?? 0),
                (int)($_SESSION['user_id'] ?? 0),
                (string)($_SESSION['full_name'] ?? '')
            );
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function approveAjAction()
    {
        header('Content-Type: application/json');
        try {
            (new WorkInstances())->approve(
                (int)($_POST['id'] ?? 0),
                (int)($_SESSION['user_id'] ?? 0),
                (string)($_SESSION['full_name'] ?? ''),
                (string)($_POST['notes'] ?? '')
            );
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function rejectAjAction()
    {
        header('Content-Type: application/json');
        try {
            (new WorkInstances())->reject(
                (int)($_POST['id'] ?? 0),
                (int)($_SESSION['user_id'] ?? 0),
                (string)($_SESSION['full_name'] ?? ''),
                (string)($_POST['reason'] ?? '')
            );
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function reopenAjAction()
    {
        header('Content-Type: application/json');
        try {
            (new WorkInstances())->reopen((int)($_POST['id'] ?? 0), (int)($_SESSION['user_id'] ?? 0));
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function cancelAjAction()
    {
        header('Content-Type: application/json');
        try {
            (new WorkInstances())->cancel(
                (int)($_POST['id'] ?? 0),
                (int)($_SESSION['user_id'] ?? 0),
                (string)($_POST['reason'] ?? '')
            );
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }
}
