<?php
ob_start();
require_once __DIR__ . '/../core/auth.php';
require_once __DIR__ . '/../core/response.php';
cors();
$user = Auth::requireToken();
$db   = DB::get();
$act  = $_GET['action'] ?? $_POST['action'] ?? 'list';

try {
    switch ($act) {

        case 'list':
            $q = '%' . $db->esc($_GET['q'] ?? '') . '%';
            $status = $db->esc($_GET['status'] ?? '');
            $where = $status ? "AND q.status = '$status'" : '';
            $rows = $db->select(
                "SELECT q.*, c.clients_name
                 FROM quotes q
                 LEFT JOIN clients c ON c.record_id = q.clients_id
                 WHERE (q.quotes_name LIKE ? OR c.clients_name LIKE ?) $where
                 ORDER BY q.record_id DESC",
                'ss', $q, $q
            );
            json_ok($rows);

        case 'get':
            $id = (int)($_GET['id'] ?? 0);
            $row = $db->selectOne(
                "SELECT q.*, c.clients_name, c.email, c.cell, c.address
                 FROM quotes q LEFT JOIN clients c ON c.record_id = q.clients_id
                 WHERE q.record_id = ?", 'i', $id
            );
            if (!$row) json_err('Not found', 404);
            json_ok($row);

        case 'add':
            
            $clientId = (int)($_POST['clients_id'] ?? 0);
            $content  = trim($_POST['quote_content'] ?? '');
            $total    = (float)($_POST['total'] ?? 0);
            $desc     = trim($_POST['description'] ?? '');
            $dateSent = trim($_POST['date_sent'] ?? '');
            $dateExp  = trim($_POST['date_exp'] ?? '');
            $status   = trim($_POST['status'] ?? 'DRAFT');
            if (!$clientId) json_err('Client required');

            // Get next quote number from actual MAX in quotes table (reliable even if company counter is out of sync)
            $maxRow  = $db->selectOne("SELECT COALESCE(MAX(quote_no), 0) AS mx FROM quotes");
            $quoteNo = (int)$maxRow['mx'] + 1;
            $db->execute("UPDATE company SET quote_no = ? WHERE record_id = 1", 'i', $quoteNo);
            $name = (string)$quoteNo; // auto-name = quote number

            $dateCreated = date('Y-m-d');
            $id = $db->execute(
                "INSERT INTO quotes (quote_no, quotes_name, quote_content, total, clients_id, status, date_created, date_sent, date_exp, description)
                 VALUES (?,?,?,?,?,?,?,?,?,?)",
                'issdiissss', $quoteNo, $name, $content, $total, $clientId, $status, $dateCreated, $dateSent, $dateExp, $desc
            );
            Auth::log((int)$user['user_id'], "CREATED QUOTE #$quoteNo", 'quotes', $id);
            json_ok(['id' => $id, 'quote_no' => $quoteNo], 'Quote created');

        case 'update':
            $id      = (int)($_POST['id'] ?? 0);
            $name    = trim($_POST['quotes_name'] ?? '');
            $clientId = (int)($_POST['clients_id'] ?? 0);
            $content = trim($_POST['quote_content'] ?? '');
            $total   = (float)($_POST['total'] ?? 0);
            $desc    = trim($_POST['description'] ?? '');
            $dateSent = trim($_POST['date_sent'] ?? '');
            $dateExp = trim($_POST['date_exp'] ?? '');
            $status  = trim($_POST['status'] ?? 'DRAFT');
            if (!$id) json_err('ID required');
            $db->execute(
                "UPDATE quotes SET quotes_name=?, clients_id=?, quote_content=?, total=?, status=?, date_sent=?, date_exp=?, description=? WHERE record_id=?",
                'sisdsssi', $name, $clientId, $content, $total, $status, $dateSent, $dateExp, $desc, $id
            );
            // also fix type binding: s,i,s,d,s,s,s,s,i
            Auth::log((int)$user['user_id'], "UPDATED QUOTE #$id", 'quotes', $id);
            json_ok(null, 'Quote updated');

        case 'convert':
            // Convert quote to invoice
            $id = (int)($_POST['id'] ?? 0);
            $quote = $db->selectOne("SELECT * FROM quotes WHERE record_id = ?", 'i', $id);
            if (!$quote) json_err('Quote not found', 404);
            $company = $db->selectOne("SELECT invoice_no FROM company WHERE record_id = 1");
            $invoiceNo = ($company['invoice_no'] ?? 0) + 1;
            $db->execute("UPDATE company SET invoice_no = ? WHERE record_id = 1", 'i', $invoiceNo);
            $dateCreated = date('Y-m-d');
            $dateDue = date('Y-m-d', strtotime('+30 days'));
            $invId = $db->execute(
                "INSERT INTO invoices (invoice_no, invoices_name, quotes_id, invoice_content, total, clients_id, status, date_created, date_sent, date_due, description)
                 VALUES (?,?,?,?,?,?,?,?,?,?,?)",
                'iiisdisssss', $invoiceNo, $invoiceNo, $id, $quote['quote_content'], $quote['total'],
                $quote['clients_id'], 'DRAFT', $dateCreated, '', $dateDue, $quote['description']
            );
            $db->execute("UPDATE quotes SET status='CONVERTED' WHERE record_id=?", 'i', $id);
            Auth::log((int)$user['user_id'], "CONVERTED QUOTE #$id TO INVOICE #$invoiceNo", 'quotes', $id);
            json_ok(['invoice_id' => $invId], 'Converted to invoice');

        default:
            json_err('Unknown action');
    }
} catch (Exception $e) {
    json_err($e->getMessage(), 500);
}