<?php 
ob_start();
header('Content-Type: application/json');
ini_set('display_errors', 0);
error_reporting(E_ALL);

$response = ['success' => false, 'message' => 'ERROR DESCONOCIDO'];

try {
    require_once '../core/api.php';

    $data = json_decode(file_get_contents('php://input'), true);

    if (empty($data['id'])) throw new Exception('ID REQUERIDO');
    $id = filter_var($data['id'], FILTER_VALIDATE_INT);

    // INICIO TRANSACCIÓN
    $pdo->beginTransaction();

    // --- CASO 1: SOLO CAMBIO DE ESTADO ---
    if (isset($data['status']) && count($data) <= 3) { 
        
        $stmtCheck = $pdo->prepare("SELECT status_seguimiento FROM quotes WHERE id = ?");
        $stmtCheck->execute([$id]);
        $current = $stmtCheck->fetch(PDO::FETCH_ASSOC);
        
        $new_status = $data['status'];
        $new_funnel = $current['status_seguimiento'];

        // Lógica de negocio para el funnel
        if ($new_status === 'sent' && empty($current['status_seguimiento'])) $new_funnel = 'Cotización Enviada';
        elseif ($new_status === 'generated') $new_funnel = null;
        elseif ($new_status === 'approved') $new_funnel = 'Cotización Ganada';
        elseif ($new_status === 'rejected') $new_funnel = 'Cotización Perdida';

        $stmt = $pdo->prepare("UPDATE quotes SET status = ?, status_seguimiento = ? WHERE id = ?");
        $stmt->execute([$new_status, $new_funnel, $id]);
        $response['message'] = 'ESTADO ACTUALIZADO';
    } 
    // --- CASO 2: EDICIÓN COMPLETA (Items) ---
    else {
        // Recalcular totales en servidor (NO CONFIAR EN EL FRONTEND)
        $items = $data['items'] ?? [];
        $subtotal = 0;
        foreach ($items as $item) {
            $price = floatval($item[1]);
            $qty = intval($item[2]);
            $subtotal += ($price * $qty);
        }
        $tax_rate = floatval($data['tax_rate'] ?? 0);
        $total = $subtotal + ($subtotal * ($tax_rate / 100));

        // Actualizar cabecera (tabla quotes)
        $stmtHeader = $pdo->prepare("UPDATE quotes SET estimate_date = ?, tax_rate = ?, subtotal = ?, total_amount = ?, updated_at = NOW() WHERE id = ?");
        $stmtHeader->execute([$data['estimate_date'], $tax_rate, $subtotal, $total, $id]);
        
        // Reemplazar items (tabla quotes_items)
        $pdo->prepare("DELETE FROM quotes_items WHERE quote_id = ?")->execute([$id]);
        
        if (!empty($items)) {
            $stmtItem = $pdo->prepare("INSERT INTO quotes_items (quote_id, description, unit_price, quantity) VALUES (?, ?, ?, ?)");
            foreach ($items as $item) {
                $stmtItem->execute([$id, $item[0], $item[1], $item[2]]);
            }
        }
        $response['message'] = 'COTIZACIÓN GUARDADA';
    }

    $pdo->commit();
    $response['success'] = true;

} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
    $response['message'] = $e->getMessage();
}

if (ob_get_level() > 0) ob_end_clean();
echo json_encode($response);
exit;
?>