<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

header("Content-Type: application/json");
require 'db_config.php';

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

if (!$data || !isset($data['id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid JSON or missing estimate ID.']);
    exit;
}

$estimate_id = $data['id'];

try {
    $pdo->beginTransaction();

    // 1. Update the main estimate details
    $totalAmount = 0;
    foreach ($data['lineItems'] as $item) {
        $totalAmount += $item['quantity'] * $item['unitPrice'];
    }

    $sql = "UPDATE estimates SET customer_id = :customer_id, status = :status, issue_date = :issue_date, total_amount = :total_amount WHERE id = :id";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':customer_id' => $data['customerId'],
        ':status' => $data['status'],
        ':issue_date' => $data['issueDate'],
        ':total_amount' => $totalAmount,
        ':id' => $estimate_id
    ]);

    // 2. Delete old line items
    $pdo->prepare("DELETE FROM estimate_line_items WHERE estimate_id = ?")->execute([$estimate_id]);

    // 3. Insert the new line items
    $sql_items = "INSERT INTO estimate_line_items (estimate_id, product_id, quantity, unit_price) VALUES (:estimate_id, :product_id, :quantity, :unit_price)";
    $stmt_items = $pdo->prepare($sql_items);
    foreach ($data['lineItems'] as $item) {
        $stmt_items->execute([
            ':estimate_id' => $estimate_id,
            ':product_id' => $item['productId'],
            ':quantity' => $item['quantity'],
            ':unit_price' => $item['unitPrice']
        ]);
    }

    $pdo->commit();
    echo json_encode(['status' => 'success', 'message' => 'Estimate updated successfully.']);

} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    echo json_encode(['status' => 'error', 'message' => 'Failed to update estimate: ' . $e->getMessage()]);
}
?>