<?php
// shikanisha.kts.php is the file where you store your database connection details
require_once "shikanisha.kts.php";
session_start();

// check if there is a connection error
if(mysqli_connect_error()){
    echo "<script>
        alert('Cannot connect to database');
        window.location.href='../login.php';
    </script>";
}

if($_SESSION['total'] > 0) {
    $pay_method = 'cash';
    $paid_amount = 0;
    $total = $_SESSION['total'];
    $telephone = $_SESSION['phone'];
    $seller = $_SESSION['user'];
    $date = date("Y-m-d H:i:s");
    
    $query1 = "INSERT INTO transaction_receipts(payment_method, amount_received, total, phone_number, seller_name, seller_date)
              VALUES('$pay_method', $paid_amount, $total, '$telephone', '$seller', '$date')";
    if(mysqli_query($conn, $query1)) {
        $receipt_id = mysqli_insert_id($conn);
        $query2 = "INSERT INTO sales(product_name, selling_price, quantity, product_id, subtotal, trans_id)
                   VALUES(?, ?, ?, ?, ?, ?)";
        $stmt = mysqli_prepare($conn, $query2);
        if($stmt) {
            mysqli_stmt_bind_param($stmt, "siiiii", $name, $price, $quantity, $id, $subtotal, $receipt_id);
            foreach($_SESSION['cart'] as $key => $value) {
                $name = $value['name'];
                $price = $value['price'];
                $quantity = $value['qty'];
                $id = $value['id'];
                $subtotal = $value['price'] * $value['qty'];
                mysqli_stmt_execute($stmt);
            }
            mysqli_stmt_close($stmt);
           
            echo "<script>
                    alert('Items sent to bill successfully');
                    window.location.href='../accprint.php';
                  </script>";
        } else {
            echo "Error: " . mysqli_error($conn);
        }
    } else {
        echo "<script>
                alert('SQL Error');
                window.location.href='../accomodation.php';
              </script>";
    }
} else {
    echo "<script>
                window.location.href='../accomodation.php';
              </script>";
}
?>
