<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include('includes/config.php');
include_once('includes/settings.php');
include_once('includes/security.php');

if (strlen($_SESSION['login']) == 0) {
    header('location:login.php');
    exit();
}

// Redirect if cart is empty
if (empty($_SESSION['cart'])) {
    header('location:my-cart.php');
    exit();
}

// Handle Order Submission from Checkout
if (isset($_POST['place_order'])) {
    $uid = $_SESSION['id'];
    $paymethod = db_prepare($con, $_POST['payment_method']);
    $delivery_method = db_prepare($con, $_POST['delivery_method']);
    $delivery_fee = floatval($_POST['delivery_fee']);
    $gps_address = ($delivery_method == 'door' && isset($_POST['gps_address'])) ? db_prepare($con, $_POST['gps_address']) : "";
    $door_state = ($delivery_method == 'door' && isset($_POST['door_state'])) ? intval($_POST['door_state']) : "NULL";
    $door_city = ($delivery_method == 'door' && isset($_POST['door_city'])) ? intval($_POST['door_city']) : "NULL";

    // In a real app, you'd insert the order here, including the delivery info
    // For now, let's update the existing orders (inserted by my-cart.php)
    // with the payment method and potentially a delivery fee if you have a column for it.
    $pickup_id = ($delivery_method == 'pickup') ? intval($_POST['pickup_station_id']) : "NULL";

    // Update orders with all checkout information
    mysqli_query($con, "UPDATE orders SET 
        paymentMethod='$paymethod', 
        delivery_method='$delivery_method',
        delivery_fee='$delivery_fee',
        pickup_station_id=$pickup_id, 
        gps_address='$gps_address', 
        delivery_state=$door_state, 
        delivery_city=$door_city 
        WHERE userId='$uid' AND paymentMethod IS NULL");

    // Store delivery info in session for the next step if needed
    $_SESSION['paymethod'] = $paymethod;
    $_SESSION['delivery_method'] = $delivery_method;
    $_SESSION['delivery_fee'] = $delivery_fee;

    unset($_SESSION['cart']);
    header('location:order-history.php');
    exit();
}

$uid = $_SESSION['id'];
$user_query = mysqli_query($con, "SELECT u.*, ud.billingAddress, ud.billingCity, ud.billingState, ud.billingPincode, 
                                  ud.shippingAddress, ud.shippingCity, ud.shippingState, ud.shippingPincode, 
                                  ud.ship_same_as_billing, ud.preferred_pickup_id,
                                  ps.station_name as pref_station_name, ps.state_id as pref_state_id, ps.city_id as pref_city_id
                                  FROM users u 
                                  LEFT JOIN user_details ud ON u.id = ud.user_id 
                                  LEFT JOIN pickup_stations ps ON ud.preferred_pickup_id = ps.id
                                  WHERE u.id='$uid'");
$user_data = mysqli_fetch_array($user_query);
// Ensure null safety for address fields
$user_data['shippingAddress'] = $user_data['shippingAddress'] ?? '';
$user_data['shippingCity'] = $user_data['shippingCity'] ?? '';
$user_data['shippingState'] = $user_data['shippingState'] ?? '';
$user_data['shippingPincode'] = $user_data['shippingPincode'] ?? '';
$user_data['billingAddress'] = $user_data['billingAddress'] ?? '';
$user_data['billingCity'] = $user_data['billingCity'] ?? '';
$user_data['billingState'] = $user_data['billingState'] ?? '';
$user_data['billingPincode'] = $user_data['billingPincode'] ?? '';

// Final Address Validation before allowing checkout view
$billing_incomplete = empty($user_data['billingAddress']) || empty($user_data['billingCity']) || empty($user_data['billingState']);
$shipping_incomplete = ($user_data['ship_same_as_billing'] != 1) && (empty($user_data['shippingAddress']) || empty($user_data['shippingCity']) || empty($user_data['shippingState']));

if ($billing_incomplete || $shipping_incomplete) {
    header('location:my-cart.php');
    exit();
}

// Pickup and Door Delivery settings (Defaults)
$def_pickup_fee = floatval(get_setting('pickup_fee', 11.00));
$def_door_delivery_fee = floatval(get_setting('door_delivery_fee', 25.00));
$free_shipping_threshold = floatval(get_setting('free_shipping_threshold', 150.00));

// Calculate cumulative delivery fees based on cart content
$total_items_price = 0;
$total_pickup_fee = 0;
$total_door_fee = 0;

$cart_pids = array_keys($_SESSION['cart']);
if (!empty($cart_pids)) {
    $p_query = mysqli_query($con, "SELECT id, productPrice, shipping_pickup_fee, shipping_door_fee FROM products WHERE id IN(" . implode(',', $cart_pids) . ")");
    while ($p_row = mysqli_fetch_array($p_query)) {
        $qty = $_SESSION['cart'][$p_row['id']]['quantity'];
        $total_items_price += ($qty * $p_row['productPrice']);

        // Use product-specific fee if set, otherwise use system default
        $p_pickup = ($p_row['shipping_pickup_fee'] !== null) ? floatval($p_row['shipping_pickup_fee']) : $def_pickup_fee;
        $p_door = ($p_row['shipping_door_fee'] !== null) ? floatval($p_row['shipping_door_fee']) : $def_door_delivery_fee;

        $total_pickup_fee += ($p_pickup * $qty);
        $total_door_fee += ($p_door * $qty);
    }
}

// Apply free shipping logic if threshold is met
if ($total_items_price >= $free_shipping_threshold && $free_shipping_threshold > 0) {
    $total_pickup_fee = 0;
    $total_door_fee = 0;
}

$active_fee = $total_pickup_fee; // Default to pickup
?>

<!DOCTYPE html>
<html lang="en">
<?php include('includes/head.php'); ?>

<body class="cnt-home">
    <header class="header-style-1">
        <?php include('includes/top-header.php'); ?>
        <?php include('includes/main-header.php'); ?>
        <?php include('includes/menu-bar.php'); ?>
    </header>

    <div class="breadcrumb mt-2">
        <div class="container">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="my-cart.php">Cart</a></li>
                    <li class="breadcrumb-item active">Checkout</li>
                </ol>
            </nav>
        </div>
    </div>

    <div class="body-content">
        <div class="container">
            <div class="checkout-container py-4">
                <form method="post" id="checkout-form">
                    <div class="row">
                        <!-- Left Side: Addresses and Delivery -->
                        <div class="col-lg-8">
                            <!-- Delivery Method Section -->
                            <div class="checkout-card mb-4">
                                <div class="card-header bg-white py-3">
                                    <h5 class="mb-0 fw-bold"><i class="fa fa-truck me-2 text-primary"></i> 1. Delivery
                                        Method</h5>
                                </div>
                                <div class="card-body">
                                    <div class="delivery-options">
                                        <div class="delivery-option mb-3">
                                            <input type="radio" name="delivery_method" id="delivery_pickup"
                                                value="pickup" data-fee="<?php echo $total_pickup_fee; ?>" checked>
                                            <label for="delivery_pickup"
                                                class="delivery-label p-3 border rounded w-100 cursor-pointer">
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <div>
                                                        <span class="fw-bold d-block">Pickup Station</span>
                                                        <small class="text-muted">Collect your order from a nearby
                                                            pickup point</small>
                                                    </div>
                                                    <span class="fee-badge">Ghs.
                                                        <?php echo number_format($total_pickup_fee, 2); ?></span>
                                                </div>
                                                <!-- Pickup Station Selection -->
                                                <div id="pickup_location_selector" class="mt-3 pt-3 border-top"
                                                    style="<?php echo (isset($_POST['delivery_method']) && $_POST['delivery_method'] != 'pickup') ? 'display:none;' : ''; ?>">
                                                    <div class="row g-2">
                                                        <div class="col-md-4">
                                                            <label class="small fw-bold">Select State</label>
                                                            <select class="form-select form-select-sm" id="p_state">
                                                                <option value="">State</option>
                                                                <?php
                                                                $s_q = mysqli_query($con, "SELECT * FROM states ORDER BY state_name ASC");
                                                                while ($s_r = mysqli_fetch_array($s_q)) {
                                                                    $selected = ($s_r['id'] == $user_data['pref_state_id']) ? 'selected' : '';
                                                                    echo "<option value='" . $s_r['id'] . "' $selected>" . htmlentities($s_r['state_name']) . "</option>";
                                                                }
                                                                ?>
                                                            </select>
                                                        </div>
                                                        <div class="col-md-4">
                                                            <label class="small fw-bold">Select City</label>
                                                            <select class="form-select form-select-sm" id="p_city" <?php echo empty($user_data['pref_city_id']) ? 'disabled' : ''; ?>>
                                                                <option value="">City</option>
                                                                <?php
                                                                if (!empty($user_data['pref_state_id'])) {
                                                                    $c_q = mysqli_query($con, "SELECT * FROM cities WHERE state_id=" . $user_data['pref_state_id'] . " ORDER BY city_name ASC");
                                                                    while ($c_r = mysqli_fetch_array($c_q)) {
                                                                        $selected = ($c_r['id'] == $user_data['pref_city_id']) ? 'selected' : '';
                                                                        echo "<option value='" . $c_r['id'] . "' $selected>" . htmlentities($c_r['city_name']) . "</option>";
                                                                    }
                                                                }
                                                                ?>
                                                            </select>
                                                        </div>
                                                        <div class="col-md-4">
                                                            <label class="small fw-bold">Select Hub</label>
                                                            <select name="pickup_station_id"
                                                                class="form-select form-select-sm" id="p_station" <?php echo empty($user_data['preferred_pickup_id']) ? 'disabled' : ''; ?> required>
                                                                <option value="">Hub</option>
                                                                <?php
                                                                if (!empty($user_data['pref_city_id'])) {
                                                                    $ps_q = mysqli_query($con, "SELECT * FROM pickup_stations WHERE city_id=" . $user_data['pref_city_id'] . " AND status=1 ORDER BY station_name ASC");
                                                                    while ($ps_r = mysqli_fetch_array($ps_q)) {
                                                                        $selected = ($ps_r['id'] == $user_data['preferred_pickup_id']) ? 'selected' : '';
                                                                        echo "<option value='" . $ps_r['id'] . "' $selected>" . htmlentities($ps_r['station_name']) . "</option>";
                                                                    }
                                                                }
                                                                ?>
                                                            </select>
                                                        </div>
                                                    </div>
                                                    <div id="station_info" class="mt-2 small text-primary fw-bold">
                                                        <?php if (!empty($user_data['pref_station_name']))
                                                            echo "<i class='fa fa-info-circle me-1'></i> Selected: " . $user_data['pref_station_name']; ?>
                                                    </div>
                                                </div>
                                            </label>
                                        </div>

                                        <div class="delivery-option">
                                            <input type="radio" name="delivery_method" id="delivery_door" value="door"
                                                data-fee="<?php echo $total_door_fee; ?>">
                                            <label for="delivery_door"
                                                class="delivery-label p-3 border rounded w-100 cursor-pointer">
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <div>
                                                        <span class="fw-bold d-block">Door Delivery</span>
                                                        <small class="text-muted">Delivered directly to your home or
                                                            office address</small>
                                                    </div>
                                                    <span class="fee-badge">Ghs.
                                                        <?php echo number_format($total_door_fee, 2); ?></span>
                                                </div>
                                                <!-- Door Delivery Location Selector -->
                                                <div id="door_location_selector" class="mt-3 pt-3 border-top"
                                                    style="display:none;">
                                                    <div class="row g-2 mb-3">
                                                        <div class="col-md-6">
                                                            <label class="small fw-bold">Select State *</label>
                                                            <select class="form-select form-select-sm" id="d_state"
                                                                name="door_state" readonly
                                                                style="pointer-events: none; background-color: #e9ecef;">
                                                                <?php
                                                                // Default to Eastern Region (ID 1)
                                                                $s_q = mysqli_query($con, "SELECT * FROM states WHERE id = 1");
                                                                while ($s_r = mysqli_fetch_array($s_q)) {
                                                                    echo "<option value='" . $s_r['id'] . "' selected>" . htmlentities($s_r['state_name']) . "</option>";
                                                                }
                                                                ?>
                                                            </select>
                                                        </div>
                                                        <div class="col-md-6">
                                                            <label class="small fw-bold">Select City *</label>
                                                            <select class="form-select form-select-sm" id="d_city"
                                                                name="door_city" readonly
                                                                style="pointer-events: none; background-color: #e9ecef;">
                                                                <?php
                                                                // Default to Nsawam (ID 1)
                                                                $c_q = mysqli_query($con, "SELECT * FROM cities WHERE id = 1");
                                                                while ($c_r = mysqli_fetch_array($c_q)) {
                                                                    echo "<option value='" . $c_r['id'] . "' selected>" . htmlentities($c_r['city_name']) . "</option>";
                                                                }
                                                                ?>
                                                            </select>
                                                        </div>
                                                    </div>
                                                    <div class="mb-0">
                                                        <label class="small fw-bold">Ghana Post GPS Address *</label>
                                                        <input type="text" name="gps_address" id="gps_address"
                                                            class="form-control form-control-sm"
                                                            placeholder="e.g. GA-123-4567">
                                                        <small class="text-muted" style="font-size: 0.75rem;">Providing
                                                            your GPS address helps us find you faster.</small>
                                                    </div>
                                                </div>
                                            </label>
                                        </div>
                                    </div>
                                    <input type="hidden" name="delivery_fee" id="delivery_fee_input"
                                        value="<?php echo $total_pickup_fee; ?>">
                                </div>
                            </div>

                            <!-- Payment Method Section -->
                            <div class="checkout-card mb-4">
                                <div class="card-header bg-white py-3">
                                    <h5 class="mb-0 fw-bold"><i class="fa fa-credit-card me-2 text-primary"></i> 2.
                                        Payment Method</h5>
                                </div>
                                <div class="card-body">
                                    <div class="payment-options">
                                        <div class="form-check mb-2">
                                            <input class="form-check-input" type="radio" name="payment_method"
                                                id="pay_cod" value="COD" checked>
                                            <label class="form-check-label" for="pay_cod">Cash on Delivery (COD)</label>
                                        </div>
                                        <div class="form-check mb-2">
                                            <input class="form-check-input" type="radio" name="payment_method"
                                                id="pay_momo" value="Mobile Money">
                                            <label class="form-check-label" for="pay_momo">Mobile Money (MTN, Vodafone,
                                                AirtelTigo)</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="payment_method"
                                                id="pay_card" value="Card">
                                            <label class="form-check-label" for="pay_card">Debit / Credit Card</label>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Shipping Address Section -->
                            <div class="checkout-card mb-4">
                                <div class="card-header bg-white py-3">
                                    <h5 class="mb-0 fw-bold"><i class="fa fa-map-marker me-2 text-primary"></i> 3.
                                        Shipping Details</h5>
                                </div>
                                <div class="card-body">
                                    <div class="current-address p-3 bg-light rounded border mb-3">
                                        <p class="mb-1 fw-bold">
                                            <?php echo htmlentities($user_data['name'] ?? $_SESSION['username']); ?>
                                        </p>
                                        <p class="mb-1 small"><?php echo htmlentities($user_data['shippingAddress']); ?>
                                        </p>
                                        <p class="mb-0 small text-muted">
                                            <?php echo htmlentities($user_data['shippingCity'] . ', ' . $user_data['shippingState']); ?>
                                        </p>
                                    </div>
                                    <a href="my-cart.php" class="btn btn-link btn-sm p-0"><i
                                            class="fa fa-edit me-1"></i> Change Address</a>
                                </div>
                            </div>
                        </div>

                        <!-- Right Side: Order Summary -->
                        <div class="col-lg-4">
                            <div class="summary-card sticky-top" style="top: 80px;">
                                <div class="card-header bg-dark text-white py-3">
                                    <h5 class="mb-0 fw-bold">Order Summary</h5>
                                </div>
                                <div class="card-body p-0">
                                    <div class="p-3">
                                        <?php
                                        $sum_query = mysqli_query($con, "SELECT id, productName, productPrice FROM products WHERE id IN(" . implode(',', array_keys($_SESSION['cart'])) . ")");
                                        while ($sum_row = mysqli_fetch_array($sum_query)) {
                                            $qty = $_SESSION['cart'][$sum_row['id']]['quantity'];
                                            $sub = $qty * $sum_row['productPrice'];
                                            ?>
                                            <div class="d-flex justify-content-between mb-2 small">
                                                <span class="text-truncate" style="max-width: 200px;"><?php echo $qty; ?>x
                                                    <?php echo $sum_row['productName']; ?></span>
                                                <span>Ghs. <?php echo number_format($sub, 2); ?></span>
                                            </div>
                                        <?php } ?>
                                    </div>

                                    <div class="border-top p-3 bg-light">
                                        <div class="d-flex justify-content-between mb-2">
                                            <span>Subtotal</span>
                                            <span id="summary_subtotal"
                                                data-value="<?php echo $total_items_price; ?>">Ghs.
                                                <?php echo number_format($total_items_price, 2); ?></span>
                                        </div>
                                        <div class="d-flex justify-content-between mb-2 text-primary">
                                            <span id="delivery_method_text">Delivery Fee (Pickup)</span>
                                            <span id="summary_delivery_fee">Ghs.
                                                <?php echo number_format($total_pickup_fee, 2); ?></span>
                                        </div>
                                        <hr>
                                        <div class="d-flex justify-content-between mb-0 h5 fw-bold text-dark">
                                            <span>Total</span>
                                            <span id="summary_total">Ghs.
                                                <?php echo number_format($total_items_price + $total_pickup_fee, 2); ?></span>
                                        </div>
                                    </div>

                                    <div class="p-3">
                                        <button type="submit" name="place_order"
                                            class="btn btn-primary w-100 py-3 fw-bold shadow-sm">
                                            PLACE ORDER NOW
                                        </button>
                                        <p class="text-center mt-3 small text-muted">
                                            By placing your order, you agree to our <br> <a href="#">Terms &
                                                Conditions</a>
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <style>
        .checkout-card,
        .summary-card {
            border: 1px solid #ddd;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .delivery-label {
            transition: all 0.2s;
            display: block;
        }

        .delivery-option input[type="radio"] {
            display: none;
        }

        .delivery-option input[type="radio"]:checked+.delivery-label {
            border-color: #E8663D !important;
            background-color: rgba(232, 102, 61, 0.05);
            box-shadow: 0 0 0 1px #E8663D;
        }

        .cursor-pointer {
            cursor: pointer;
        }

        .fee-badge {
            background: #f8f9fa;
            padding: 4px 10px;
            border-radius: 20px;
            font-weight: 700;
            font-size: 14px;
            color: #282828;
            border: 1px solid #eee;
        }

        .btn-primary {
            background-color: #E8663D;
            border-color: #E8663D;
        }

        .btn-primary:hover {
            background-color: #d25532;
            border-color: #d25532;
        }

        .text-primary {
            color: #E8663D !important;
        }
    </style>

    <script src="assets/js/jquery-1.11.1.min.js"></script>
    <script>
        $(document).ready(function () {
            // Toggle Pickup/Door Selectors
            $('input[name="delivery_method"]').change(function () {
                const fee = parseFloat($(this).data('fee'));
                const subtotal = parseFloat($('#summary_subtotal').data('value'));
                const method = $(this).val();

                if (method === 'pickup') {
                    $('#pickup_location_selector').slideDown();
                    $('#door_location_selector').slideUp();
                    $('#p_station').prop('required', true);
                    $('#d_state, #d_city, #gps_address').prop('required', false);
                } else {
                    $('#pickup_location_selector').slideUp();
                    $('#door_location_selector').slideDown();
                    $('#p_station').prop('required', false);
                    $('#d_state, #d_city, #gps_address').prop('required', true);
                }

                // Update text
                $('#delivery_method_text').text('Delivery Fee (' + (method === 'pickup' ? 'Pickup' : 'Door Delivery') + ')');

                // Update Fee
                $('#summary_delivery_fee').text('Ghs. ' + fee.toFixed(2));
                $('#delivery_fee_input').val(fee);

                // Update Grand Total
                const total = subtotal + fee;
                $('#summary_total').text('Ghs. ' + total.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }));
            });

            // AJAX: State -> City (Pickup)
            $('#p_state').change(function () {
                var state_id = $(this).val();
                if (state_id) {
                    $('#p_city').prop('disabled', false).html('<option value="">Loading...</option>');
                    $('#p_station').prop('disabled', true).html('<option value="">Hub</option>');
                    $.ajax({
                        url: '__admin__/get_locations.php',
                        type: 'POST',
                        data: { state_id: state_id },
                        success: function (html) {
                            $('#p_city').html(html);
                        }
                    });
                } else {
                    $('#p_city').prop('disabled', true).html('<option value="">City</option>');
                    $('#p_station').prop('disabled', true).html('<option value="">Hub</option>');
                }
            });

            // AJAX: State -> City (Door Delivery)
            $('#d_state').change(function () {
                var state_id = $(this).val();
                if (state_id) {
                    $('#d_city').prop('disabled', false).html('<option value="">Loading...</option>');
                    $.ajax({
                        url: '__admin__/get_locations.php',
                        type: 'POST',
                        data: { state_id: state_id },
                        success: function (html) {
                            $('#d_city').html(html);
                        }
                    });
                } else {
                    $('#d_city').prop('disabled', true).html('<option value="">City</option>');
                }
            });

            // AJAX: City -> Hub
            $('#p_city').change(function () {
                var city_id = $(this).val();
                if (city_id) {
                    $('#p_station').prop('disabled', false).html('<option value="">Loading...</option>');
                    $.ajax({
                        url: '__admin__/get_locations.php',
                        type: 'POST',
                        data: { city_id: city_id },
                        success: function (html) {
                            $('#p_station').html(html);
                        }
                    });
                } else {
                    $('#p_station').prop('disabled', true).html('<option value="">Hub</option>');
                }
            });

            // AJAX: Save Preference
            $('#p_station').change(function () {
                var station_id = $(this).val();
                var station_name = $("#p_station option:selected").text();
                var user_id = "<?php echo $uid; ?>";

                if (station_id) {
                    $('#station_info').html('<i class="fa fa-spinner fa-spin me-1"></i> Saving preference...');
                    $.ajax({
                        url: '__admin__/get_locations.php',
                        type: 'POST',
                        data: { save_pickup_id: station_id, user_id: user_id },
                        success: function (resp) {
                            if (resp.trim() === 'success') {
                                $('#station_info').html('<i class="fa fa-check-circle me-1"></i> Saved: ' + station_name);
                            } else {
                                $('#station_info').html('<i class="fa fa-info-circle me-1"></i> Selected: ' + station_name);
                            }
                        }
                    });
                } else {
                    $('#station_info').html('');
                }
            });
    });
    </script>

    <?php include('includes/footer.php'); ?>
    <?php include('includes/foot.php'); ?>
</body>

</html>
<?php ?>