<?php
/**
 * ICYLAB OS - Quote Number Service
 *
 * Centraliza la generacion de folios de cotizacion.
 * Requiere la tabla quote_sequences(year, last_number).
 */

if (!function_exists('crm_next_quote_number')) {
    function crm_next_quote_number(PDO $pdo, $year = null, $minimumLastNumber = 1450)
    {
        $year = $year ? (int)$year : (int)date('Y');
        $minimumLastNumber = (int)$minimumLastNumber;
        $prefix = 'COT-' . $year . '-%';

        // Sincroniza la secuencia con el mayor folio existente antes de tomar el siguiente.
        $stmtMax = $pdo->prepare("\n            SELECT COALESCE(MAX(CAST(SUBSTRING_INDEX(quote_number, '-', -1) AS UNSIGNED)), 0)\n            FROM crm_quotes\n            WHERE quote_number LIKE ?\n        ");
        $stmtMax->execute(array($prefix));
        $maxExisting = (int)$stmtMax->fetchColumn();
        $currentFloor = max($minimumLastNumber, $maxExisting);

        $stmtSeed = $pdo->prepare("\n            INSERT INTO quote_sequences (`year`, last_number)\n            VALUES (?, ?)\n            ON DUPLICATE KEY UPDATE last_number = GREATEST(last_number, VALUES(last_number))\n        ");
        $stmtSeed->execute(array($year, $currentFloor));

        $stmtLock = $pdo->prepare("SELECT last_number FROM quote_sequences WHERE `year` = ? FOR UPDATE");
        $stmtLock->execute(array($year));
        $lastNumber = (int)$stmtLock->fetchColumn();

        $nextNumber = $lastNumber + 1;

        $stmtUpdate = $pdo->prepare("UPDATE quote_sequences SET last_number = ? WHERE `year` = ?");
        $stmtUpdate->execute(array($nextNumber, $year));

        return 'COT-' . $year . '-' . str_pad((string)$nextNumber, 4, '0', STR_PAD_LEFT);
    }
}
