<?php
include("db/cn.php");

if(isset($_SESSION['user_name']) && isset($_SESSION['user_role']) && isset($_SESSION['outlet_name'])
 && isset($_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
	$outlet_address = $_SESSION['outlet_address'];
	$outlet_name = $_SESSION['outlet_name'];
   
// Check connection
if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

// Initialize a flag to track successful submission
$success = false;

// Check if data is sent via POST method
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['customer']) 
&& isset($_POST['phone']) && isset($_POST['sale_by']) && isset($_POST['paid_by'])
 && isset($_POST['product_id']) && isset($_POST['product_name']) && isset($_POST['discount_amount']) 
 && isset($_POST['product_price']) && isset($_POST['product_quantity'])) {
    // Retrieve customer details
    $customer = $_POST['customer'];
    $phone = $_POST['phone'];
    $sale_by = $_POST['sale_by'];
    $paid_by = $_POST['paid_by'];
	$discount = $_POST['discount_amount'];
    
	$date_time = date("Y-m-d");
	$orderNumber = uniqid('ORDER');
	
// Insert data into cdetail table
$sql_cdetail = "INSERT INTO cdetail (customer_name, phone_number, sale_by, outlet_name, outlet_address, paid_by, order_id) 
				VALUES ('$customer', '$phone', '$sale_by', '$outlet_name', '$outlet_address', '$paid_by', '$orderNumber')";
					
	if ($connection->query($sql_cdetail) === TRUE) {
		$success = true;
	}

    // Retrieve items table data
    $items = array(); // Initialize an empty array for items
    
    // Loop through each item
    for ($i = 0; $i < count($_POST['product_id']); $i++) {
        $item = array(
            'id' => $_POST['product_id'][$i],
            'name' => $_POST['product_name'][$i],
            'price' => $_POST['product_price'][$i],
            'quantity' => $_POST['product_quantity'][$i],
            'total' => $_POST['product_price'][$i] * $_POST['product_quantity'][$i] // Calculate total price
        );
        $items[] = $item; // Add item to the items array
        
        // Insert item details into pay_hold table
        $sql_pay_hold = "INSERT INTO pay_hold (customer_name, phone_number, sale_by, paid_by, product_name, product_id, product_price, product_quantity, product_total, tax_amount, discount_amount, total_amount, order_id, outlet_name, login_user, user_role, outlet_address, date_time)
        VALUES ('$customer', '$phone', '$userName', '$paid_by', '{$item['name']}', '{$item['id']}', '{$item['price']}', '{$item['quantity']}', '{$item['total']}', '0' ,'$discount', '0', '$orderNumber', '$outlet_name', '$userName', '$userRole', '$outlet_address', '$date_time')";

        // Execute the query
        if ($connection->query($sql_pay_hold) !== TRUE) {
            $success = false;
        }
    }
}

// Close connection
//$connection->close();
if ($success) {
    header("Location: pos.php");
    exit; // Make sure to exit after redirection to prevent further execution
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hold Transaction Details</title>
    <link rel="stylesheet" href="css/custom_css.css">
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
</head>
<body>

<div class="container">
    <h2>Hold Transaction Details</h2>
    <form id="holdForm" action="hold_pay.php" method="post"> <!-- Add an id to the form -->
        <h3>Customer Details:</h3>
        <p><strong>Customer Name:</strong> <?php echo $customer; ?></p>
        <p><strong>Phone:</strong> <?php echo $phone; ?></p>
        <p><strong>Sale By:</strong> <?php echo $sale_by; ?></p>
        <p><strong>Paid By:</strong> <?php echo $paid_by; ?></p>

        <h3>Items:</h3>
        <table class="table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Price</th>
                    <th>Quantity</th>
                    <th>Total</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($items as $item): ?>
                    <tr>
                        <td><?php echo $item['id']; ?></td>
                        <td><?php echo $item['name']; ?></td>
                        <td><?php echo $item['price']; ?></td>
                        <td><?php echo $item['quantity']; ?></td>
                        <td><?php echo $item['total']; ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <button type="button" id="submitBtn">Hold the Transaction</button> <!-- Add the submit button -->
    </form>
</div>

<!-- Add the JavaScript code to handle form submission and redirection -->
<script>
document.getElementById('submitBtn').addEventListener('click', function() {
    document.getElementById('holdForm').submit(); // Submit the form when the button is clicked
});

document.getElementById('holdForm').addEventListener('submit', function(event) {
    event.preventDefault(); // Prevent the default form submission behavior

    // Perform any necessary form validation here
    
    // Redirect after form submission
    window.location.href = 'pos.php'; // Redirect to pos.php
});
</script>
</body>
</html>

<?php }?>