<?php
// Secure session settings
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_samesite', 'Strict');
ini_set('session.cookie_secure', 1);

// Start the session
session_start();

// Regenerate session ID for security
if (!isset($_SESSION['initialized'])) {
    session_regenerate_id(true);
    $_SESSION['initialized'] = true;
}

// Check if the user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id']; // Get the user ID from the session

// Include DB connection
include './db.php';

// Check database connection
if (!$conn) {
    error_log("Database connection failed: " . mysqli_connect_error());
    header("Location: error_page.php");
    exit();
}

// Query to get all cart items for the user
$cart_items = [];
$stmt = $conn->prepare("SELECT id, machine_id, machine_type, price FROM cart WHERE user_id = ?");
if ($stmt) {
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $stmt->bind_result($id, $machine_id, $machine_type, $price);

    while ($stmt->fetch()) {
        $cart_items[] = [
            'id' => $id,
            'machine_id' => $machine_id,
            'machine_type' => $machine_type,
            'price' => $price
        ];
    }

    $stmt->close();
} else {
    error_log("Failed to prepare statement: " . $conn->error);
    header("Location: error_page.php");
    exit();
}

$stmt = $conn->prepare("SELECT COUNT(*) FROM cart WHERE user_id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();
$stmt->bind_result($notificationCount);
$stmt->fetch();
$stmt->close();

// Query to get all products
$products = [];
$product_query = $conn->prepare("SELECT id, product_name, price FROM products");
if ($product_query) {
    $product_query->execute();
    $product_query->bind_result($product_id, $product_name, $product_price);

    while ($product_query->fetch()) {
        $products[] = [
            'id' => $product_id,
            'product_name' => $product_name,
            'price' => $product_price
        ];
    }

    $product_query->close();
} else {
    error_log("Failed to prepare product query: " . $conn->error);
    header("Location: error_page.php");
    exit();
}

// Calculate total price
$total_price = 0;
foreach ($cart_items as $item) {
    $total_price += $item['price'];
}


// Close database connection
$conn->close();
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <!-- PAGE TITLE HERE -->
    <title>My Wash - Order</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="images/favicon.png">
    <link href="vendor/bootstrap-select/css/bootstrap-select.min.css" rel="stylesheet">
    <link class="main-css" href="css/style.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://kit.fontawesome.com/f2ba2ab8c2.js" crossorigin="anonymous"></script>
</head>

<body>
    <!-- Preloader -->
    <div id="preloader">
        <div class="loading-wave">
            <div class="loading-bar"></div>
            <div class="loading-bar"></div>
            <div class="loading-bar"></div>
            <div class="loading-bar"></div>
        </div>
    </div>

    <!-- Main Wrapper -->
    <div id="main-wrapper" class="show">
        <?php include './page/header.php'; ?>

        <!-- Container -->
        <div class="container mt-4">
            <div class="mb-4">
                <a href="./dashboard.php" class="btn btn-light"><i class="fa-solid fa-arrow-left"></i> Back</a>
            </div>
            <div class="row">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-header">Cart Items</div>
                        <div class="card-body">
                            <table class="table table-responsive-md">
                                <thead>
                                    <tr>
                                        <th>Product</th>
                                        <th>Machine Serial</th>
                                        <th>Price</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody class="cart-table-body">
                                    <?php foreach ($cart_items as $item): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($item['machine_type']) ?></td>
                                            <td><?= htmlspecialchars($item['machine_id']) ?></td>
                                            <td>Rp <?= number_format($item['price'], 0, ',', '.') ?></td>
                                            <td>
                                                <button class="btn btn-danger shadow btn-xs sharp remove-from-cart" data-id="<?= htmlspecialchars($item['id']) ?>">
                                                    <i class="fa fa-trash"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Total and Process Button -->
            <div class="row mt-3">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-header">
                            Total
                        </div>
                        <div class="card-body">
                            <h4 class="text-center">Total Payment: Rp <span class="total-price"><?= number_format($total_price, 0, ',', '.') ?></span></h4>
                            <button type="submit" class="btn btn-primary btn-block mt-4" id="process-now-btn">Process Now</button>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Optional Products -->
            <div class="row mt-3">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-header">Optional</div>
                        <div class="card-body">
                            <table class="table table-responsive-md">
                                <thead>
                                    <tr>
                                        <th>Product Name</th>
                                        <th>Price</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($products as $product): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($product['product_name']) ?></td>
                                            <td>Rp <?= number_format($product['price'], 0, ',', '.') ?></td>
                                            <td>
                                                <button class="btn btn-primary btn-sm add-to-cart" data-id="<?= htmlspecialchars($product['id']) ?>">
                                                    <i class="fa-solid fa-cart-shopping"></i> Add to Cart
                                                </button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="footer">
				<div class="copyright">
					<p>© Designed &amp; Developed by <a
							href="#" target="_blank">My Wash</a> <span
							class="current-year">2024</span></p>
				</div>
			</div>
    </div>

    <!-- Scripts -->
    <script src="vendor/global/global.min.js"></script>
    <script src="vendor/bootstrap-select/js/bootstrap-select.min.js"></script>
    <script src="js/custom.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const addToCartButtons = document.querySelectorAll('.add-to-cart');
    
            addToCartButtons.forEach(button => {
                button.addEventListener('click', function () {
                    const productId = this.getAttribute('data-id');
    
                    fetch('optional_add_cart.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ id: productId }),
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // Update Cart Items
                            const cartTableBody = document.querySelector('.cart-table-body');
                            cartTableBody.innerHTML = data.cart_html;
    
                            // Show success alert
                            Swal.fire({
                                icon: 'success',
                                title: 'Added to Cart!',
                                text: 'Item has been added to your cart.',
                            });
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Failed',
                                text: data.message || 'Unable to add item to cart.',
                            });
                        }
                    })
                    .catch(error => {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'An unexpected error occurred.',
                        });
                        console.error(error);
                    });
                });
            });
        });
    </script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const cartTableBody = document.querySelector('.cart-table-body');
        
            cartTableBody.addEventListener('click', function (event) {
                if (event.target.closest('.remove-from-cart')) {
                    const button = event.target.closest('.remove-from-cart');
                    const cartItemId = button.getAttribute('data-id');
        
                    fetch('remove_from_cart.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ id: cartItemId }),
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // Update Cart Items
                            cartTableBody.innerHTML = data.cart_html;
        
                            // Update Total Price
                            const totalPriceElement = document.querySelector('.total-price');
                            totalPriceElement.innerHTML = `Rp ${data.total}`;
        
                            // Show success alert
                            Swal.fire({
                                icon: 'success',
                                title: 'Removed from Cart!',
                                text: 'Item has been removed from your cart.',
                            });
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Failed',
                                text: data.message || 'Unable to remove item from cart.',
                            });
                        }
                    })
                    .catch(error => {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'An unexpected error occurred.',
                        });
                        console.error(error);
                    });
                }
            });
        });
        
        // Fungsi untuk memperbarui total harga setiap 1 detik
        setInterval(function() {
            // Kirim request Ajax untuk mendapatkan total harga keranjang dari server
            $.ajax({
                url: 'get_cart_total.php', // Endpoint untuk mendapatkan total harga
                type: 'GET',
                success: function(response) {
                    var data = JSON.parse(response);
        
                    if (data.success) {
                        // Update elemen total harga di halaman
                        $('.total-price').text(data.total);
                    } else {
                        console.error('Failed to fetch total price');
                    }
                },
                error: function() {
                    console.error('Error in Ajax request');
                }
            });
        }, 2000); // Setiap 1 detik (1000 ms)
    </script>
    <script>
        document.getElementById('process-now-btn').addEventListener('click', function() {
    // Kirim permintaan Ajax untuk memproses transaksi
    $.ajax({
        url: 'process_transaction.php', // Endpoint untuk memproses transaksi
        type: 'POST',
        success: function(response) {
            var data = JSON.parse(response);
    
            if (data.success) {
                // Redirect to complete.php with invoice_number as a query parameter
                window.location.href = 'complete.php?invoice_number=' + data.invoice_number;
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Transaction Failed',
                    text: data.message || 'There was an error processing your transaction.',
                });
            }
        },
        error: function() {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'An unexpected error occurred.',
            });
        }
    });
});
    </script>

</body>

</html>
