<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

$order_id = intval($_GET['order_id'] ?? 0);
if(!$order_id){
    echo "<script>alert('Invalid order'); window.location='restaurant_orders_list.php';</script>";
    exit;
}

// Fetch order and items
$order = $conn->query("SELECT * FROM restaurant_orders WHERE id=$order_id")->fetch_assoc();
$items = $conn->query("SELECT roi.*, rm.name, rm.category FROM restaurant_order_items roi 
                       LEFT JOIN restaurant_menu rm ON roi.menu_id = rm.id 
                       WHERE roi.order_id=$order_id")->fetch_all(MYSQLI_ASSOC);

if(!$order){
    echo "<script>alert('Order not found'); window.location='restaurant_orders_list.php';</script>";
    exit;
}

if(isset($_POST['complete_payment'])){

    $payment_method = $conn->real_escape_string($_POST['payment_method']);
    $discount = floatval($_POST['discount']);

    // Logged in user
    $created_by = $_SESSION['username'] ?? 'Unknown';
    $user_id    = $_SESSION['user_id'] ?? NULL;

    // Prevent double payment
    if($order['status'] == 'PAID'){
        echo "<script>alert('This order is already paid.'); window.location='restaurant_orders_list.php';</script>";
        exit;
    }

    // Calculate subtotal
    $subtotal = 0;

    foreach($items as $c){
        $subtotal += ($c['price'] * $c['qty']);
    }

    $grand_total = $subtotal - $discount;

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

    try{

        // ================= INSERT SALE =================
        $stmt = $conn->prepare("
            INSERT INTO sales(
                total,
                vat_total,
                discount,
                rest,
                payment_method,
                customer_id,
                sale_date,
                store_id,
                created_by,
                user_id
            ) VALUES (
                ?, ?, ?, ?, ?, ?, NOW(), ?, ?, ?
            )
        ");

        $vat_total = 0;
        $rest = 2;
        $store_id = 3;
        $customer_id = $order['customer_id'] ?? 0;

        $stmt->bind_param(
            "dddississ",
            $grand_total,
            $vat_total,
            $discount,
            $rest,
            $payment_method,
            $customer_id,
            $store_id,
            $created_by,
            $user_id
        );

        $stmt->execute();

        $sale_id = $conn->insert_id;

        // ================= INSERT SALE ITEMS =================
        foreach($items as $c){

            $product_id = $c['product_id'] ?? NULL;
            $menu_id    = $c['menu_id'];
            $price      = $c['price'];
            $qty        = $c['qty'];
            $vat        = 0;

            $stmt2 = $conn->prepare("
                INSERT INTO sale_items(
                    sale_id,
                    product_id,
                    menu_id,
                    price,
                    qty,
                    vat,
                    store_id
                ) VALUES (
                    ?, ?, ?, ?, ?, ?, ?
                )
            ");

            $stmt2->bind_param(
                "iiidiis",
                $sale_id,
                $product_id,
                $menu_id,
                $price,
                $qty,
                $vat,
                $store_id
            );

            $stmt2->execute();
        }

        // ================= UPDATE ORDER =================
        $stmt3 = $conn->prepare("
            UPDATE restaurant_orders
            SET status='PAID'
            WHERE id=?
        ");

        $stmt3->bind_param("i", $order_id);
        $stmt3->execute();

        $conn->commit();

        echo "<script>
            alert('✅ Payment completed successfully!');
            window.location='restaurant_orders_list.php';
        </script>";

        exit;

    }catch(Exception $e){

        $conn->rollback();

        echo "<div class='alert alert-danger'>
            Payment Failed: ".$e->getMessage()."
        </div>";
    }
}

?>

<!-- Custom CSS for restaurant-style menu -->
<style>
    .menu-card {
        border: 1px solid #ddd;
        border-radius: 8px;
        padding: 10px;
        margin-bottom: 10px;
        transition: 0.2s;
        background: #f9f9f9;
    }
    .menu-card:hover {
        box-shadow: 0px 3px 8px rgba(0,0,0,0.2);
    }
    .menu-name {
        font-weight: bold;
        font-size: 1rem;
    }
    .menu-category {
        font-size: 0.85rem;
        color: #666;
    }
    .menu-price {
        font-weight: bold;
        color: #1b4d32;
    }
    .subtotal-box {
        font-size: 1.1rem;
        font-weight: bold;
        text-align: right;
        margin-top: 15px;
    }
</style>

<div class="container mt-4">
     <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
    </div>
    <h3 class="text-center mb-4">💳 Process Payment for Order #<?= $order_id ?></h3>

    <!-- Display Menu Items in Card Layout -->
    <div class="row">
        <?php
        $subtotal = 0;
        foreach($items as $c):
            $total = $c['price'] * $c['qty'];
            $subtotal += $total;
        ?>
        <div class="col-md-4">
            <div class="menu-card">
                <div class="menu-name"><?= $c['name'] ?></div>
                <div class="menu-category"><?= $c['category'] ?? '' ?></div>
                <div>Qty: <?= $c['qty'] ?></div>
                <div class="menu-price">MK <?= number_format($total,2) ?></div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <div class="subtotal-box">
        Subtotal: MK <?= number_format($subtotal,2) ?>
    </div>

    <!-- Payment Form -->
    <form method="POST" class="mt-4">
        <div class="row g-3">
            <div class="col-md-4">
                <label>Discount (MK)</label>
                <input type="number" name="discount" step="0.01" value="0" class="form-control">
            </div>
            <div class="col-md-4">
               <div class="form-group">
    <label><i class="fa fa-credit-card"></i> Payment Method</label>

    <select name="payment_method" id="payment_method" class="form-control" required>
        <option value="">-- Select Method --</option>

        <option value="Cash">💵 Cash</option>
        <option value="Mobile Money">📱 Mobile Money</option>
        <option value="Airtel Money">📲 Airtel Money</option>
        <option value="TNM Mpamba">📲 TNM Mpamba</option>
        <option value="Card">💳 Card (POS)</option>
        <option value="Bank Transfer">🏦 Bank Transfer</option>
        <option value="Cheque">🧾 Cheque</option>
        <option value="Online Payment">🌐 Online Payment</option>
        <option value="Digital Wallet">👛 Digital Wallet</option>
        <option value="Other">➕ Other</option>
    </select>
</div>
             
            </div>
            <div class="col-md-4 mt-4">
                <button type="submit" name="complete_payment" class="btn btn-success w-100">
                    💳 Complete Payment
                </button>
            </div>
        </div>
    </form>
</div>
