<?php
session_start();

// Database connection
require_once 'shikanisha.kts.php';

// Check for the HTTP request method
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Assuming you have already connected to the database.

    // Add code to retrieve $customerId, $method, $descr, and $type from your form data.
    $customerId = $_POST['clientId'];
    $method = 'To Pay';
    $descr = ''; // Set a default value for $descr
    $type = 'invoice'; // Set a default value for $type
    $username = $_SESSION['user'];
    $phone = $_POST['phoneNo'];
    $amount = 0;

    // Start a transaction
    mysqli_autocommit($conn, false); // Disable autocommit

    // Flag to track the success of the entire transaction
    $transactionSuccess = true;
    $errorMessage = ''; // Initialize an error message variable

    try {
        // Step 1: Initialize the remaining quantity to sell as the total quantity of items in the cart
        $remainingQuantity = [];
        $cartDetails = [];
        $total = 0;

        foreach ($_SESSION['cartz'] as $item) {
            $itemName = $item['item_name'];
            $productid = $item['product_id'];
            $itemQuantity = intval($item['quantity']); // Convert quantity to integer
            $subtotal = floatval($item['price']) * $itemQuantity; // Calculate subtotal for each item

            // Create a unique identifier for the item based on name, attribute, and size
            $itemIdentifier = $productid;

            // If the unique identifier doesn't exist in $remainingQuantity, initialize it
            if (!isset($remainingQuantity[$itemIdentifier])) {
                $remainingQuantity[$itemIdentifier] = 0;
            }

            // Add the item's details, quantity, and subtotal to the $cartDetails array
            $cartDetails[] = [
                'name' => $itemName,
                'product_id' => $productid,
                'price' => floatval($item['price']), // Convert price to float
                'quantity' => $itemQuantity,
                'subtotal' => $subtotal,
            ];

            // Update the quantity for the unique identifier in $remainingQuantity
            $remainingQuantity[$itemIdentifier] += $itemQuantity;

            // Add the subtotal to the total
            $total += $subtotal;
        }

        // Insert the sale transaction
        $insertSaleTransactionQuery = "INSERT INTO transaction_receipts (phone_number, total, payment_method, seller_date, seller_name, amount_received) VALUES ('$phone', '$total', '$method', NOW(), '$username', '$amount')";
        if (!mysqli_query($conn, $insertSaleTransactionQuery)) {
            throw new Exception("Error inserting sale transaction: " . mysqli_error($conn));
        }

        // Get the last inserted sale_transaction ID
        $stid = mysqli_insert_id($conn);

        // Insert into client_trans table
        $sql = "INSERT INTO `client_trans`(`client_id`, `amount`, `date`, `type`, `stid`,`method`)
                VALUES ('$customerId', '$total', NOW(), '$type', '$stid', '$method')";
        if (!mysqli_query($conn, $sql)) {
            throw new Exception("Error inserting client transaction: " . mysqli_error($conn));
        }

        // Update amount_owed in client_acc table
        $sql = "UPDATE `client_acc` SET `amount_owed` = `amount_owed` + '$total' WHERE `client_id` = '$customerId'";
        if (!mysqli_query($conn, $sql)) {
            throw new Exception("Error updating client account: " . mysqli_error($conn));
        }

        // Insert into item_sales table and deduct inventory
        foreach ($cartDetails as $cartItem) {
            $itemName = mysqli_real_escape_string($conn, $cartItem['name']);
            $productid = mysqli_real_escape_string($conn, $cartItem['product_id']);
            $itemQuantity = intval($cartItem['quantity']); // Convert quantity to integer
            $subtotal = floatval($cartItem['subtotal']);
            $price = floatval($cartItem['price']); // Corrected variable

            // Deduct the sold quantity from this batch
            $sqlUpdateInventory = "UPDATE products SET shop_quantity = shop_quantity - '$itemQuantity' WHERE product_id = '$productid' ";
            if (!mysqli_query($conn, $sqlUpdateInventory)) {
                throw new Exception("Error updating inventory: " . mysqli_error($conn));
            }

            // Insert a sales record into item_sales table
            $sqlInsertItemSales = "INSERT INTO sales (trans_id, product_name, product_id, quantity, selling_price, subtotal) VALUES ('$stid', '$itemName', '$productid', '$itemQuantity', '$price', '$subtotal')";
            if (!mysqli_query($conn, $sqlInsertItemSales)) {
                throw new Exception("Error inserting item sales: " . mysqli_error($conn));
            }
        }

        // Commit the transaction if all queries were successful
    mysqli_commit($conn);

        $responseData = [
            'success' => true,
            'message' => 'Transaction successful!',
            'error' => '',
        ];
        header('Content-Type: application/json');
        echo json_encode($responseData);
    } catch (Exception $e) {
        // Something went wrong, rollback the transaction
        mysqli_rollback($conn);
        $transactionSuccess = false;
        $errorMessage = $e->getMessage();
        
        $responseData = [
            'success' => false,
            'message' => 'Transaction failed!',
            'error' => $errorMessage,
        ];
        header('Content-Type: application/json');
        echo json_encode($responseData);
    } finally {
        // Re-enable autocommit and close the database connection
        mysqli_autocommit($conn, true); // Re-enable autocommit
        mysqli_close($conn);
    }
} else {
    // Invalid request method
    header('HTTP/1.0 405 Method Not Allowed');
}
?>