<?php
class NestTendersController extends Controller
{
    public function indexAction()
    {
        $filter = ['q' => trim((string)($_GET['q'] ?? '')), 'category' => (string)($_GET['category'] ?? ''), 'status' => (string)($_GET['status'] ?? '')];
        $m = new NestTenders();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('NestTenders/index', [
            'page_title' => 'NeST Public Tenders',
            'rows'       => $m->listAll($filter),
            'filter'     => $filter,
        ]);
    }

    public function addAction()
    {
        $m = new NestTenders();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
            $id = $m->create($_POST);
            header('Location: ' . PROOT . 'NestTenders/view/' . $id); return;
        }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('NestTenders/form', ['page_title' => 'Add NeST Tender']);
    }

    public function viewAction($id = 0)
    {
        $id = (int)$id;
        $m = new NestTenders();
        $tender = $m->find($id);
        if (!$tender) { header('HTTP/1.1 404 Not Found'); echo 'Tender not found'; return; }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('NestTenders/view', [
            'page_title' => 'Tender · ' . htmlspecialchars($tender['tender_title']),
            'tender'     => $tender,
        ]);
    }

    public function convertToLeadAjAction()
    {
        header('Content-Type: application/json');
        try {
            $id = (int)($_POST['tender_id'] ?? 0);
            $userId   = (int)($_SESSION['user_id'] ?? 0);
            $userName = (string)($_SESSION['full_name'] ?? '');
            $leadId = (new NestTenders())->convertToLead($id, $userId, $userName);
            echo json_encode(['ok' => true, 'lead_id' => $leadId]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }
}
