<?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) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid JSON data.']);
    exit;
}

try {
    $pdo->beginTransaction();

    // 1. Insert into estimates table
    $totalAmount = 0;
    foreach ($data['lineItems'] as $item) {
        $totalAmount += $item['quantity'] * $item['unitPrice'];
    }

    $sql = "INSERT INTO estimates (customer_id, estimate_number, status, issue_date, total_amount) VALUES (:customer_id, :estimate_number, :status, :issue_date, :total_amount)";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':customer_id' => $data['customerId'],
        ':estimate_number' => $data['estimateNumber'],
        ':status' => $data['status'],
        ':issue_date' => $data['issueDate'],
        ':total_amount' => $totalAmount
    ]);

    // 2. Get the new estimate's ID
    $estimate_id = $pdo->lastInsertId();

    // 3. Insert into estimate_line_items table
    $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 created successfully.', 'id' => $estimate_id]);

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