<?php
// actions/checkout.php
session_start();
require_once('../config/db.php');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ../cart.php');
    exit;
}

$cart = $_SESSION['cart'] ?? [];
if (empty($cart)) {
    header('Location: ../cart.php');
    exit;
}

// Get customer values
$customerName  = $_POST['customer_name']  ?? '';
$customerPhone = $_POST['customer_phone'] ?? '';

// Calculate total
$total = 0;
foreach ($cart as $c) $total += (float)$c['Total'];

try {
    $pdo->beginTransaction();

    // Create invoice number
    $invoiceNo = 'INV-' . date('YmdHis') . '-' . strtoupper(substr(md5(uniqid('',true)),0,6));

    // Insert master (NOW includes customer fields)
    $stmt = $pdo->prepare("
        INSERT INTO sales_master (InvoiceNo, CustomerName, CustomerPhone, TotalAmount, CreatedBy)
        VALUES (?, ?, ?, ?, ?)
    ");

    $createdBy = $_SESSION['user_name'] ?? null;

    $stmt->execute([
        $invoiceNo,
        $customerName,
        $customerPhone,
        $total,
        $createdBy
    ]);

    $saleID = $pdo->lastInsertId();

    // Insert items + update stock
    $itemStmt = $pdo->prepare("
        INSERT INTO sale_items (SaleID, ProductID, Quantity, PricePerUnit, TotalAmount)
        VALUES (?, ?, ?, ?, ?)
    ");

    $stockStmt = $pdo->prepare("
        UPDATE products 
        SET StockQuantity = StockQuantity - ? 
        WHERE ProductID = ? AND StockQuantity >= ?
    ");

    foreach ($cart as $c) {

        $itemStmt->execute([
            $saleID,
            $c['ProductID'],
            (int)$c['Qty'],
            $c['Price'],
            $c['Total']
        ]);

        $stockStmt->execute([
            (int)$c['Qty'],
            $c['ProductID'],
            (int)$c['Qty']
        ]);

        if ($stockStmt->rowCount() === 0) {
            throw new Exception('Insufficient stock for product ' . $c['ProductID']);
        }
    }

    $pdo->commit();

    // Clear cart + redirect
    $_SESSION['last_sale_id'] = $saleID;
    unset($_SESSION['cart']);

    header('Location: ../receipt.php?id=' . $saleID);
    exit;

} catch (Exception $e) {

    $pdo->rollBack();
    $_SESSION['error'] = 'Checkout failed: ' . $e->getMessage();

    header('Location: ../checkout.php');
    exit;
}
