<?php
class BusinessLeadsController extends Controller
{
    public function indexAction()
    {
        $filter = [
            'stage'   => (string)($_GET['stage']   ?? ''),
            'q'       => trim((string)($_GET['q']  ?? '')),
            'overdue' => !empty($_GET['overdue']),
        ];
        $m = new BusinessLeads();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('BusinessLeads/index', [
            'page_title' => 'Business Leads',
            'rows'       => $m->listAll($filter),
            'filter'     => $filter,
        ]);
    }

    public function addAction()    { $this->handleForm(null); }
    public function editAction($id = 0) { $this->handleForm((int)$id); }

    private function handleForm(?int $id): void
    {
        $m = new BusinessLeads();
        $userId = (int)($_SESSION['user_id'] ?? 0);
        $userName = (string)($_SESSION['full_name'] ?? '');

        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
            if ($id === null) { $id = $m->create($_POST, $userId, $userName); }
            else              { $m->update($id, $_POST, $userId); }
            header('Location: ' . PROOT . 'BusinessLeads/view/' . $id);
            return;
        }

        $existing = $id ? $m->find($id) : null;
        // Customers dropdown (up to 200 recent)
        $db = new DB();
        $customers = $db->mySelect("SELECT c0d, fname, lname, customer_no FROM customers WHERE deleted = 0 ORDER BY fname, lname LIMIT 500", []) ?: [];

        $this->view->setLayout($this->roleLayout());
        $this->view->render('BusinessLeads/form', [
            'page_title' => $id ? 'Edit Lead' : 'Add Lead',
            'lead'       => $existing,
            'customers'  => $customers,
            'stages'     => BusinessLeads::STAGES,
        ]);
    }

    public function viewAction($id = 0)
    {
        $id = (int)$id;
        $m = new BusinessLeads();
        $lead = $m->find($id);
        if (!$lead) { header('HTTP/1.1 404 Not Found'); echo 'Lead not found'; return; }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('BusinessLeads/view', [
            'page_title'  => 'Lead · ' . htmlspecialchars($lead['lead_name']),
            'lead'        => $lead,
            'follow_ups'  => $m->followUps($id),
            'stages'      => BusinessLeads::STAGES,
        ]);
    }

    /* ── AJAX endpoints ─────────────────────────────────────────────────── */

    public function addFollowUpAjAction()
    {
        header('Content-Type: application/json');
        try {
            $leadId = (int)($_POST['lead_id'] ?? 0);
            $date   = trim((string)($_POST['follow_date'] ?? date('Y-m-d')));
            $note   = trim((string)($_POST['follow_note'] ?? ''));
            if ($leadId <= 0 || $note === '') throw new InvalidArgumentException('Lead + note required.');
            (new BusinessLeads())->addFollowUp($leadId, $date, $note, (int)($_SESSION['user_id'] ?? 0));
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function setStageAjAction()
    {
        header('Content-Type: application/json');
        try {
            $leadId = (int)($_POST['lead_id'] ?? 0);
            $stage  = trim((string)($_POST['stage'] ?? ''));
            (new BusinessLeads())->setStage($leadId, $stage, (int)($_SESSION['user_id'] ?? 0));
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

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

    /* ── Exports ───────────────────────────────────────────────────────── */

    public function xlsxAction() { $this->exportRegister('xlsx'); }
    public function pdfAction()  { $this->exportRegister('pdf'); }

    private function exportRegister(string $format): void
    {
        $filter = ['stage' => (string)($_GET['stage'] ?? ''), 'q' => trim((string)($_GET['q'] ?? '')), 'overdue' => !empty($_GET['overdue'])];
        $rows = (new BusinessLeads())->listAll($filter);
        $data = []; $sum = 0;
        foreach ($rows as $l) {
            $data[] = [$l['lead_name'], $l['customer_name'], $l['lead_source'], $l['project_type'],
                       (float)$l['opportunity_value'], $l['status'], $l['next_action_date'] ?? '', $l['owner_name']];
            $sum += (float)$l['opportunity_value'];
        }
        $columns = [
            ['label' => 'Lead',           'width' => 32, 'align' => 'L'],
            ['label' => 'Customer',       'width' => 26, 'align' => 'L'],
            ['label' => 'Source',         'width' => 14, 'align' => 'L'],
            ['label' => 'Type',           'width' => 12, 'align' => 'L'],
            ['label' => 'Opportunity',    'width' => 18, 'align' => 'R', 'type' => 'money'],
            ['label' => 'Stage',          'width' => 14, 'align' => 'L'],
            ['label' => 'Next action',    'width' => 14, 'align' => 'L', 'type' => 'date'],
            ['label' => 'Owner',          'width' => 20, 'align' => 'L'],
        ];
        $totals = [['label' => 'Total pipeline', 'values' => [null, null, null, null, $sum, null, null, null]]];
        $title  = 'Business Leads · Pipeline';
        $sub    = date('Y-m-d') . '  ·  ' . count($rows) . ' lead(s)';
        $fname  = 'business_leads_' . date('Y-m-d');
        if ($format === 'xlsx') {
            ExportHelper::xlsxDownload($fname . '.xlsx', 'Leads', $columns, $data, $totals, ['title' => $title, 'subtitle' => $sub]);
        } else {
            ExportHelper::pdfDownload($fname . '.pdf', $title, $sub, $columns, $data, $totals, 'L');
        }
    }
}
