<?php
// checkout.php
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/facebook-pixel.php'; // Add this line

// Check if user is logged in
if (!isLoggedIn()) {
    header('Location: login.php?redirect=checkout.php');
    exit;
}

// Get cart items
$cart_items = getCartItems();

// If cart is empty, redirect to cart page
if (empty($cart_items)) {
    header('Location: cart.php');
    exit;
}

// ========================================
// TRACK INITIATE CHECKOUT EVENT
// ========================================
if (!empty(FACEBOOK_PIXEL_ID) && !empty($cart_items)) {
    $checkout_data = [
        'currency' => 'BDT',
        'value' => getCartTotal(),
        'num_items' => getCartCount(),
        'contents' => []
    ];
    
    foreach ($cart_items as $item) {
        $checkout_data['contents'][] = [
            'id' => $item['product_id'],
            'quantity' => $item['quantity'],
            'item_price' => $item['price']
        ];
    }
    
    $user_data = [
        'url' => (isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
    ];
    
    trackFacebookEvent('InitiateCheckout', $checkout_data, $user_data);
}

// Calculate totals
$subtotal = getCartTotal();
$shipping_charge = floatval(getSetting($pdo, 'shipping_charge') ?: 70);
$discount = 0;
$total = $subtotal + $shipping_charge - $discount;

// Get user data
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch();

// Get delivery charges
$delivery_charges = [
    ['id' => 1, 'name' => 'In Dhaka City', 'charge' => 70],
    ['id' => 2, 'name' => 'Saver, Keranigonj, Gazipur & Narayanganj', 'charge' => 100],
    ['id' => 3, 'name' => 'Other Districts', 'charge' => 120]
];

include __DIR__ . '/includes/header.php';
?>
<!-- Rest of checkout.php content -->

<style>
/* ===== Checkout Styles ===== */
.checkout_area {
    padding: 45px 0;
}

.checkout_form {
    background: #fff;
    padding: 30px;
    border-radius: 12px;
    border: 1px solid #e2e8f0;
}

.checkout_form_title h3 {
    font-size: 24px;
    font-weight: 700;
    color: #1e293b;
    margin-bottom: 20px;
}

.checkout_form_group {
    margin-bottom: 18px;
    position: relative;
}

.checkout_form_group label {
    display: block;
    font-weight: 500;
    font-size: 14px;
    color: #334155;
    margin-bottom: 5px;
}

.checkout_form_group input,
.checkout_form_group textarea,
.checkout_form_group select {
    width: 100%;
    padding: 12px 45px 12px 15px;
    border: 2px solid #e2e8f0;
    border-radius: 8px;
    font-size: 15px;
    transition: all 0.3s ease;
    background: #f8fafc;
}

.checkout_form_group input:focus,
.checkout_form_group textarea:focus,
.checkout_form_group select:focus {
    border-color: #047dc3;
    background: #fff;
    box-shadow: 0 0 0 3px rgba(4, 125, 195, 0.1);
    outline: none;
}

.checkout_form_group i {
    position: absolute;
    right: 15px;
    bottom: 14px;
    color: #94a3b8;
    font-size: 16px;
}

.checkout_form_checkbox_group h4 {
    font-size: 16px;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 12px;
}

.checkout_form_checkbox {
    padding: 10px 15px;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    margin-bottom: 8px;
    transition: all 0.3s ease;
    cursor: pointer;
}

.checkout_form_checkbox:last-child {
    margin-bottom: 0;
}

.checkout_form_checkbox:hover {
    border-color: #047dc3;
    background: #f8fafc;
}

.checkout_form_checkbox input[type="radio"] {
    margin-right: 10px;
    accent-color: #047dc3;
    width: 16px;
    height: 16px;
    cursor: pointer;
}

.checkout_form_checkbox label {
    cursor: pointer;
    font-size: 14px;
    color: #334155;
}

.checkout_form_btn {
    margin-top: 20px;
}

.checkout_form_btn_link {
    width: 100%;
    padding: 14px;
    background: #047dc3;
    color: #fff;
    border: none;
    border-radius: 8px;
    font-size: 18px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
}

.checkout_form_btn_link:hover {
    background: #0369a1;
}

.checkout_form_btn_link:disabled {
    opacity: 0.7;
    cursor: not-allowed;
}

/* ===== Order Summary ===== */
.checkout_order_summary {
    background: #fff;
    padding: 30px;
    border-radius: 12px;
    border: 1px solid #e2e8f0;
}

.apply_coupon_group {
    margin-bottom: 20px;
}

.apply_coupon_item {
    display: flex;
    gap: 10px;
}

.apply_coupon_item input {
    flex: 1;
    padding: 10px 15px;
    border: 2px solid #e2e8f0;
    border-radius: 8px;
    font-size: 14px;
    transition: all 0.3s ease;
}

.apply_coupon_item input:focus {
    border-color: #047dc3;
    outline: none;
    box-shadow: 0 0 0 3px rgba(4, 125, 195, 0.1);
}

.apply_coupon_item_link {
    padding: 10px 25px;
    background: #047dc3;
    color: #fff;
    border: none;
    border-radius: 8px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
}

.apply_coupon_item_link:hover {
    background: #0369a1;
    color: #fff;
}

#coupon_valid {
    color: #22c55e;
    font-size: 14px;
    margin-top: 8px;
    display: none;
}

#coupon_invalid {
    color: #ef4444;
    font-size: 14px;
    margin-top: 8px;
    display: none;
}

/* ===== Order Table ===== */
.order_summary_table {
    overflow-x: auto;
}

.order_summary_table table {
    width: 100%;
    border-collapse: collapse;
}

.order_summary_table thead tr {
    border-bottom: 2px solid #e2e8f0;
}

.order_summary_table thead th {
    padding: 12px 8px;
    text-align: left;
    font-weight: 600;
    color: #64748b;
    font-size: 13px;
}

.order_summary_table tbody tr {
    border-bottom: 1px solid #f1f5f9;
}

.order_summary_table tbody td {
    padding: 12px 8px;
    vertical-align: middle;
}

.checkout_product_td_left {
    padding-left: 0 !important;
}

.checkout_product_td_right {
    text-align: right;
    padding-right: 0 !important;
}

.checkout_product_name_image {
    display: flex;
    align-items: center;
    gap: 12px;
}

.checkout_product_name_image img {
    width: 50px;
    height: 50px;
    object-fit: cover;
    border-radius: 8px;
}

.products_checkout_name p {
    margin: 0;
    font-size: 14px;
    color: #1e293b;
}

.products_checkout_name p:last-child {
    font-size: 12px;
    color: #94a3b8;
}

.checkout_product_qty {
    display: flex;
    align-items: center;
}

.checkout_product_qty_minus,
.checkout_product_qty_plus {
    width: 30px;
    height: 30px;
    border: 1px solid #e2e8f0;
    background: transparent;
    border-radius: 4px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
}

.checkout_product_qty_minus:hover,
.checkout_product_qty_plus:hover {
    background: #047dc3;
    color: #fff;
    border-color: #047dc3;
}

.checkout_product_qty input {
    width: 40px;
    height: 30px;
    text-align: center;
    border: 1px solid #e2e8f0;
    border-left: none;
    border-right: none;
    font-size: 14px;
}

.checkout_product_price p {
    margin: 0;
    font-size: 14px;
    font-weight: 500;
    color: #1e293b;
}

.checkout_product_total_price p {
    margin: 0;
    font-size: 14px;
    font-weight: 600;
    color: #047dc3;
}

.checkout_product_delete_icon_link {
    color: #ef4444;
    transition: all 0.3s ease;
    cursor: pointer;
    text-decoration: none;
}

.checkout_product_delete_icon_link:hover {
    color: #dc2626;
}

/* ===== Price Summary ===== */
.price_summary_table_cell {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f1f5f9;
}

.price_summary_table_cell:last-child {
    border-bottom: none;
    padding-bottom: 0;
}

.price_summary_table_cell strong {
    font-weight: 500;
    color: #1e293b;
    font-size: 15px;
}

.price_summary_table_cell strong:last-child {
    font-weight: 600;
    color: #047dc3;
}

/* ===== Responsive ===== */
@media (max-width: 768px) {
    .checkout_form {
        padding: 20px;
    }
    
    .checkout_order_summary {
        padding: 20px;
    }
    
    .checkout_form_title h3 {
        font-size: 20px;
    }
    
    .checkout_product_qty input {
        width: 35px;
    }
}

@media (max-width: 576px) {
    .checkout_area {
        padding: 20px 0;
    }
    
    .apply_coupon_item {
        flex-direction: column;
    }
    
    .apply_coupon_item_link {
        width: 100%;
        justify-content: center;
    }
}
</style>

<div class="content">
    <!-- Checkout Area Start -->
    <section class="checkout_area section_padding">
        <form id="order_form">
            <div class="container">
                <div class="row gy-4">
                    <!-- Left Column: Form -->
                    <div class="col-xxl-6 col-xl-6 col-lg-6 col-md-12 col-12">
                        <div class="checkout_form">
                            <div class="checkout_form_title">
                                <h3>Please Order Now</h3>
                            </div>
                            
                            <div class="checkout_form_group">
                                <label>Full Name</label>
                                <input type="text" required name="name" value="<?php echo $user['name'] ?? ''; ?>" placeholder="Full Name">
                                <i class="fa-regular fa-user"></i>
                            </div>
                            
                            <div class="checkout_form_group">
                                <label>Mobile Number</label>
                                <input type="text" name="mobile_no" value="<?php echo $user['phone'] ?? ''; ?>" placeholder="01xxxxxxxxx" maxlength="11" minlength="11" onkeyup="setNumber(this.value, 1)" oninput="if(this.value.length > 11) this.value = this.value.slice(0, 11);">
                                <i class="fa-solid fa-phone"></i>
                            </div>
                            
                            <input type="hidden" id="free_delivery" value="" name="free_delivery">
                            <input type="hidden" id="show_city_sub_city" value="0">
                            
                            <!-- Delivery Area -->
                            <div class="checkout_form_checkbox_group">
                                <h4>Delivery Area</h4>
                                <?php foreach ($delivery_charges as $index => $charge): ?>
                                <div class="checkout_form_checkbox form-check">
                                    <input required class="form-check-input" value="<?php echo $charge['charge']; ?>" 
                                           <?php echo $index === 0 ? 'checked' : ''; ?> 
                                           onclick="shippingChargeBySelectArea(this.id, <?php echo $charge['charge']; ?>, )" 
                                           type="radio" name="shipping_charge" id="<?php echo $charge['id']; ?>">
                                    <label class="form-check-label" for="<?php echo $charge['id']; ?>">
                                        <?php echo $charge['name']; ?> - <?php echo $charge['charge']; ?>TK
                                    </label>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            
                            <div class="checkout_form_group">
                                <label>Full Address</label>
                                <input type="text" required name="address" value="<?php echo $user['address'] ?? ''; ?>" placeholder="Full Address">
                                <i class="fa-solid fa-location-dot"></i>
                            </div>
                            
                            <div class="checkout_form_group">
                                <label>Delivery Note</label>
                                <input type="text" name="note" value="" placeholder="Delivery Note">
                                <i class="fa-regular fa-comment"></i>
                            </div>
                            
                            <div class="checkout_form_btn">
                                <button id="order_form_submit" class="checkout_form_btn_link">
                                    <i class="fa-solid fa-cart-shopping"></i>
                                    Order Submit
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Right Column: Order Summary -->
                    <div class="col-xxl-6 col-xl-6 col-lg-6 col-md-12 col-12">
                        <div class="checkout_order_summary">
                            <!-- Coupon -->
                            <div class="apply_coupon_group">
                                <input type="hidden" id="coupon_amount" name="coupon_amount">
                                <div class="apply_coupon_item">
                                    <input type="text" id="coupon_name" name="coupon" placeholder="Coupon Code">
                                    <a id="coupon_apply" class="apply_coupon_item_link">Apply</a>
                                </div>
                                <span id="coupon_valid" style="color: green; display:none;">Congratulations. This Coupon is Valid.</span>
                                <span id="coupon_invalid" style="color: red; display:none;">Oops Sorry! This Coupon is Invalid.</span>
                            </div>
                            
                            <!-- Order Items -->
                            <div class="order_summary_table">
                                <table>
                                    <thead>
                                        <tr>
                                            <th class="checkout_product_td_left">Product</th>
                                            <th class="checkout_product_th_qty">Qty</th>
                                            <th class="checkout_product_th_price">Price</th>
                                            <th class="checkout_product_th_total_price">Total</th>
                                            <th class="checkout_product_td_right">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody id="check_out_carts">
                                        <?php foreach ($cart_items as $key => $item): ?>
                                        <tr>
                                            <td class="checkout_product_td_left">
                                                <div class="checkout_product_name_image">
                                                    <img src="<?php echo ASSETS_URL; ?>images/products/<?php echo $item['image'] ?: 'default.jpg'; ?>" alt="<?php echo $item['name']; ?>">
                                                    <div class="products_checkout_name">
                                                        <p><?php echo substr($item['name'], 0, 30) . '...'; ?></p>
                                                        <?php if (!empty($item['attributes'])): ?>
                                                            <?php foreach ($item['attributes'] as $attr => $val): ?>
                                                            <p><?php echo $attr; ?>: <?php echo $val; ?></p>
                                                            <?php endforeach; ?>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="checkout_product_qty">
                                                    <div id="<?php echo $key; ?>" onclick="cartDecrement(this.id)" class="checkout_product_qty_minus">
                                                        <i class="fa-solid fa-minus"></i>
                                                    </div>
                                                    <input type="text" class="product_qty" value="<?php echo $item['quantity']; ?>">
                                                    <div id="<?php echo $key; ?>" onclick="cartIncrement(this.id)" class="checkout_product_qty_plus">
                                                        <i class="fa-solid fa-plus"></i>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="checkout_product_price">
                                                    <p><?php echo number_format($item['price']); ?> TK</p>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="checkout_product_total_price">
                                                    <p><?php echo number_format($item['price'] * $item['quantity']); ?> TK</p>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="checkout_product_delete_icon">
                                                    <a id="<?php echo $key; ?>" onclick="miniCartRemove(this.id)" class="checkout_product_delete_icon_link">
                                                        <i class="fa-solid fa-trash"></i>
                                                    </a>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            
                            <!-- Price Summary -->
                            <div>
                                <div class="price_summary_table_cell">
                                    <strong>Sub Total :</strong>
                                    <input id="cart_sub_total" type="hidden" value="<?php echo $subtotal; ?>">
                                    <strong id="show_cart_sub_total"><?php echo number_format($subtotal); ?> TK</strong>
                                </div>
                                <div class="price_summary_table_cell">
                                    <strong>Shipping Charge :</strong>
                                    <strong id="show_shipping_charge"><?php echo number_format($shipping_charge); ?> TK</strong>
                                </div>
                                <div class="price_summary_table_cell">
                                    <strong>Discount Amount :</strong>
                                    <strong id="show_discount"><?php echo number_format($discount); ?> TK</strong>
                                </div>
                                <div class="price_summary_table_cell">
                                    <strong>Payable Amount :</strong>
                                    <strong id="show_payable"><?php echo number_format($total); ?> TK</strong>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </section>
</div>

<script>
// ========================================
// SHIPPING CHARGE
// ========================================
var shipping_charge = <?php echo $shipping_charge; ?>;
var sub_total = <?php echo $subtotal; ?>;
var discount = 0;
var coupon = null;

function shippingChargeBySelectArea(id, charge, free_delivery) {
    if (charge > 0 && free_delivery != 1) {
        shipping_charge = charge;
    } else {
        shipping_charge = 0;
    }
    orderSummaryCalculation(shipping_charge);
}

// ========================================
// ORDER SUMMARY CALCULATION
// ========================================
function orderSummaryCalculation(charge = 0) {
    var cart_subtotal = parseFloat($('#cart_sub_total').val()) || 0;
    var delivery_charge = parseFloat(charge) || 0;
    var discount_amount = parseFloat($('#coupon_amount').val()) || 0;
    
    var total_amount = cart_subtotal + delivery_charge - discount_amount;
    
    $('#show_shipping_charge').text(delivery_charge + ' TK');
    $('#show_discount').text(discount_amount + ' TK');
    $('#show_payable').text(total_amount + ' TK');
}

// ========================================
// CART OPERATIONS
// ========================================
function cartIncrement(rowId) {
    var qty = $('.product_qty').val();
    var increment_value = parseInt(qty) + 1;
    
    $.ajax({
        type: 'POST',
        url: 'update-cart.php',
        dataType: 'json',
        data: {
            key: rowId,
            qty: increment_value
        },
        success: function(data) {
            if (data.success) {
                location.reload();
            }
        }
    });
}

function cartDecrement(rowId) {
    var qty = $('.product_qty').val();
    var decrement_value = parseInt(qty) == 1 ? parseInt(qty) : parseInt(qty) - 1;
    
    $.ajax({
        type: 'POST',
        url: 'update-cart.php',
        dataType: 'json',
        data: {
            key: rowId,
            qty: decrement_value
        },
        success: function(data) {
            if (data.success) {
                location.reload();
            }
        }
    });
}

function miniCartRemove(rowId) {
    if (confirm('Remove this item from cart?')) {
        $.ajax({
            type: 'POST',
            url: 'update-cart.php',
            dataType: 'json',
            data: {
                key: rowId,
                qty: 0
            },
            success: function(data) {
                if (data.success) {
                    location.reload();
                }
            }
        });
    }
}

// ========================================
// COUPON APPLY
// ========================================
$('#coupon_apply').click(function() {
    var coupon_name = $('#coupon_name').val();
    
    $.ajax({
        type: 'POST',
        url: 'apply-coupon.php',
        dataType: 'json',
        data: {
            coupon: coupon_name,
            subtotal: <?php echo $subtotal; ?>
        },
        success: function(res) {
            if (res.success) {
                coupon = res.coupon;
                $('#coupon_amount').val(res.discount_amount);
                $('#coupon_valid').show();
                $('#coupon_invalid').hide();
                orderSummaryCalculation(shipping_charge);
                showToast(res.message, 'success');
            } else {
                $('#coupon_valid').hide();
                $('#coupon_invalid').show();
                showToast(res.message, 'error');
            }
        }
    });
});

// ========================================
// ORDER SUBMIT
// ========================================
$('#order_form').submit(function(e) {
    e.preventDefault();
    
    // Validate form
    var name = $('input[name="name"]').val();
    var mobile_no = $('input[name="mobile_no"]').val();
    var address = $('input[name="address"]').val();
    var shipping_charge = $('input[name="shipping_charge"]:checked').val();
    
    if (!name) {
        showToast('Please enter your name', 'error');
        return;
    }
    
    if (!mobile_no || mobile_no.length < 11) {
        showToast('Please enter a valid 11-digit mobile number', 'error');
        return;
    }
    
    if (!address) {
        showToast('Please enter your address', 'error');
        return;
    }
    
    if (!shipping_charge) {
        showToast('Please select a delivery area', 'error');
        return;
    }
    
    // Disable submit button
    var $btn = $('#order_form_submit');
    $btn.prop('disabled', true);
    $btn.html('<i class="fa-solid fa-spinner fa-spin"></i> Processing...');
    
    var formData = new FormData(this);
    formData.append('subtotal', <?php echo $subtotal; ?>);
    formData.append('total', parseFloat($('#show_payable').text().replace(' TK', '')));
    formData.append('discount', parseFloat($('#coupon_amount').val()) || 0);
    formData.append('user_id', <?php echo $_SESSION['user_id']; ?>);
    
    $.ajax({
        url: 'process-order.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(res) {
            if (res.success) {
                showToast('Order placed successfully!', 'success');
                window.location.href = 'order-success.php?invoice=' + res.invoice_no;
            } else {
                showToast(res.message || 'Failed to place order', 'error');
                $btn.prop('disabled', false);
                $btn.html('<i class="fa-solid fa-cart-shopping"></i> Order Submit');
            }
        },
        error: function() {
            showToast('Something went wrong. Please try again.', 'error');
            $btn.prop('disabled', false);
            $btn.html('<i class="fa-solid fa-cart-shopping"></i> Order Submit');
        }
    });
});

// ========================================
// SET NUMBER FOR INCOMPLETE ORDER
// ========================================
function setNumber(val, incomplete_order_system) {
    // Optional: Save incomplete order data
}

// ========================================
// TOAST NOTIFICATION
// ========================================
function showToast(message, type) {
    var colors = {
        success: '#22c55e',
        error: '#ef4444',
        warning: '#f59e0b',
        info: '#3b82f6'
    };
    
    var toast = $('<div>').css({
        position: 'fixed',
        top: '20px',
        right: '20px',
        padding: '12px 24px',
        background: colors[type] || colors.info,
        color: '#fff',
        borderRadius: '8px',
        zIndex: 9999,
        boxShadow: '0 5px 20px rgba(0,0,0,0.15)',
        animation: 'slideIn 0.3s ease'
    }).text(message);
    
    $('body').append(toast);
    setTimeout(function() {
        toast.fadeOut(300, function() { $(this).remove(); });
    }, 3000);
}

// CSS animation for toast
var style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0%); opacity: 1; }
    }
`;
document.head.appendChild(style);
</script>



<?php include __DIR__ . '/includes/footer.php'; ?>