<?php
session_start();

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode([
        "status" => "error",
        "message" => "Unauthorized Access."
    ]);
    exit;
}

include_once "../config/database.php";

if (!isset($_SESSION['cart']) || count($_SESSION['cart']) == 0) {
    echo json_encode([
        "status" => "error",
        "message" => "Cart is empty."
    ]);
    exit;
}

$customer_id = isset($_POST['customer_id']) && $_POST['customer_id'] != ''
    ? (int)$_POST['customer_id']
    : NULL;

$payment_method = mysqli_real_escape_string(
    $conn,
    trim($_POST['payment_method'] ?? 'Cash')
);

$discount = (float)($_POST['discount'] ?? 0);
$tax       = (float)($_POST['tax'] ?? 0);
$paid      = (float)($_POST['paid'] ?? 0);

$subtotal = 0;

foreach ($_SESSION['cart'] as $item) {

    $subtotal += ($item['price'] * $item['qty']);

}

$total = ($subtotal - $discount) + $tax;

if ($total < 0) {
    $total = 0;
}

if ($paid < $total) {

    echo json_encode([
        "status" => "error",
        "message" => "Paid amount is less than Total."
    ]);

    exit;
}

$change_amount = $paid - $total;

$invoice_no = "INV" . date("YmdHis");

mysqli_begin_transaction($conn);

try {

    foreach ($_SESSION['cart'] as $product_id => $item) {

        $product_id = (int)$product_id;

        $stockQuery = mysqli_query(
            $conn,
            "SELECT stock
             FROM products
             WHERE id='$product_id'
             FOR UPDATE"
        );

        if (!$stockQuery || mysqli_num_rows($stockQuery) == 0) {

            throw new Exception("Product not found.");

        }

        $stockData = mysqli_fetch_assoc($stockQuery);

        if ($stockData['stock'] < $item['qty']) {

            throw new Exception(
                $item['name'] . " has insufficient stock."
            );

        }

    }

    $customerValue = is_null($customer_id)
        ? "NULL"
        : $customer_id;

    $insertSale = mysqli_query(
        $conn,
        "INSERT INTO sales
        (
            invoice_no,
            customer_id,
            subtotal,
            discount,
            tax,
            total,
            payment_method,
            paid,
            change_amount
        )
        VALUES
        (
            '$invoice_no',
            $customerValue,
            '$subtotal',
            '$discount',
            '$tax',
            '$total',
            '$payment_method',
            '$paid',
            '$change_amount'
        )"
    );

    if (!$insertSale) {

        throw new Exception("Unable to create Sale.");

    }

    $sale_id = mysqli_insert_id($conn);
        foreach ($_SESSION['cart'] as $product_id => $item) {

        $product_id = (int)$product_id;

        $qty = (int)$item['qty'];

        $price = (float)$item['price'];

        $line_total = $qty * $price;

        $insertItem = mysqli_query(
            $conn,
            "INSERT INTO sale_items
            (
                sale_id,
                product_id,
                quantity,
                price,
                total
            )
            VALUES
            (
                '$sale_id',
                '$product_id',
                '$qty',
                '$price',
                '$line_total'
            )"
        );

        if (!$insertItem) {

            throw new Exception("Unable to save sale item.");

        }

        $updateStock = mysqli_query(
            $conn,
            "UPDATE products
             SET stock = stock - $qty
             WHERE id = '$product_id'"
        );

        if (!$updateStock) {

            throw new Exception("Unable to update stock.");

        }

    }
        mysqli_commit($conn);

    unset($_SESSION['cart']);

    echo json_encode([
        "status"      => "success",
        "message"     => "Sale completed successfully.",
        "invoice_no"  => $invoice_no,
        "sale_id"     => $sale_id
    ]);

} catch (Exception $e) {

    mysqli_rollback($conn);

    echo json_encode([
        "status"  => "error",
        "message" => $e->getMessage()
    ]);

}

exit;
?>