<?php 
session_start();
require_once "shikanisha.kts.php";

$response = [];

if (mysqli_connect_error()) {
    $response = [
        'status' => 'error',
        'message' => 'Cannot connect to database'
    ];
    echo json_encode($response);
    exit(); // Stop script execution if database connection fails
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    date_default_timezone_set('Africa/Nairobi');
    $total = 0;
    foreach ($_SESSION['cart'] as $value) {
        $total += $value['price'] * floatval($value['qty']); // Accumulate the total
    }

    $seller = $_SESSION['user'];
    $phone = $_SESSION['eid'];
    $date = date("Y-m-d H:i:s"); 
    $method = 'To Pay';
    $amount = 0;
    $table = isset($_POST['client_name']) ? $_POST['client_name'] : 'Hotel';

    $conn->begin_transaction(); // Start transaction

    $query1 = "INSERT INTO transaction_receipts (payment_method, amount_received, total, phone_number, seller_name, seller_date, table_name) VALUES (?, ?, ?, ?, ?, ?, ?)";
    $stmt1 = mysqli_prepare($conn, $query1);
    mysqli_stmt_bind_param($stmt1, 'sddssss', $method, $amount, $total, $phone, $seller, $date, $table);
    $execute1 = mysqli_stmt_execute($stmt1);
    $receipt_id = mysqli_insert_id($conn);
    mysqli_stmt_close($stmt1);

    if ($execute1) {
        $all_items_inserted = true;
        $query2 = "INSERT INTO sales (product_name, selling_price, quantity, product_id, subtotal, trans_id) VALUES (?, ?, ?, ?, ?, ?)";
        $stmt2 = mysqli_prepare($conn, $query2);
        mysqli_stmt_bind_param($stmt2, "sddidd", $name, $price, $quantity, $id, $subtotal, $receipt_id);

        foreach ($_SESSION['cart'] as $value) {
            $name = $value['name'];
            $price = $value['price'];
            $quantity = floatval($value['qty']);
            $id = $value['id'];
            $subtotal = $price * $quantity;
            if (!mysqli_stmt_execute($stmt2)) {
                $all_items_inserted = false;
                $response['message'] = 'Error inserting item: ' . mysqli_stmt_error($stmt2);
                break; // Exit the loop if insertion fails
            }
        }
        mysqli_stmt_close($stmt2);

        if ($all_items_inserted) {
            $query3 = "UPDATE products SET shop_quantity = shop_quantity - ? WHERE product_id = ?";
            $stmt3 = mysqli_prepare($conn, $query3);

            foreach ($_SESSION['cart'] as $value) {
                $quantity = floatval($value['qty']);
                $id = $value['id'];
                mysqli_stmt_bind_param($stmt3, "di", $quantity, $id);
                if (!mysqli_stmt_execute($stmt3)) {
                    $all_items_inserted = false;
                    $response['message'] = 'Error updating product quantity: ' . mysqli_stmt_error($stmt3);
                    break; // Exit the loop if update fails
                }
            }
            mysqli_stmt_close($stmt3);
        }

        if ($all_items_inserted) {
            $conn->commit(); // Commit the transaction if all went well
           // Clear the session cart data
            $response = [
                'status' => 'success',
                'message' => 'Items billed successfully.',
                'redirect' => './print.php'
            ];
        } else {
            $conn->rollback(); // Rollback the transaction if any insertions failed
        }
    } else {
        $response = [
            'status' => 'error',
            'message' => 'An error occurred while creating the receipt.'
        ];
    }
    echo json_encode($response);
}

?>
