<?php
/**
 * ============================================================
 * CHECKOUT PAGE
 * ============================================================
 * Displays cart summary, shipping form, promo code, and payment options
 * All actions handled via AJAX (no page reload)
 */

// Require user login for checkout
require_once APP_PATH . '/middleware/require_user.php';
require_once APP_PATH . '/services/cart_service.php';

// Get cart items
$cartService = new CartService();
$cartItems = $cartService->getItems();
$cartTotals = $cartService->getTotals();

// Redirect to cart if empty
if (empty($cartItems)) {
    redirect(url('public/?page=cart'));
}

// Get user info for pre-filling
$user = Database::fetchOne("SELECT * FROM users WHERE id = ?", [getUserId()]);

// Page meta
$pageTitle = 'চেকআউট';
$pageDescription = 'অর্ডার সম্পন্ন করুন';

// Include header
include PUBLIC_PATH . '/includes/head.php';
include PUBLIC_PATH . '/includes/navbar.php';
?>

<main class="py-4">
    <div class="container">
        <!-- Breadcrumb -->
        <nav aria-label="breadcrumb" class="mb-4">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="<?= url('public/') ?>">হোম</a></li>
                <li class="breadcrumb-item"><a href="<?= url('public/?page=cart') ?>">কার্ট</a></li>
                <li class="breadcrumb-item active">চেকআউট</li>
            </ol>
        </nav>

        <h2 class="mb-4"><i class="bi bi-credit-card me-2"></i>চেকআউট</h2>

        <form id="checkoutForm" method="POST">
            <?= csrf_field() ?>
            
            <!-- Hidden fields for promo -->
            <input type="hidden" name="promo_id" id="applied-promo-id" value="">
            <input type="hidden" name="promo_code" id="applied-promo-code" value="">
            <input type="hidden" name="payment_method" id="payment-method" value="">
            
            <div class="row g-4">
                <!-- Left Column: Forms -->
                <div class="col-lg-8">
                    
                    <!-- Shipping Information -->
                    <div class="checkout-section">
                        <h5><i class="bi bi-truck me-2"></i>শিপিং তথ্য</h5>
                        
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="shipping_name" class="form-label">পুরো নাম <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="shipping_name" name="shipping_name" 
                                       value="<?= sanitize($user['full_name'] ?? '') ?>" required>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="shipping_phone" class="form-label">মোবাইল নম্বর <span class="text-danger">*</span></label>
                                <input type="tel" class="form-control" id="shipping_phone" name="shipping_phone" 
                                       value="<?= sanitize($user['phone'] ?? '') ?>" placeholder="01XXXXXXXXX" required>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="shipping_email" class="form-label">ইমেইল (ঐচ্ছিক)</label>
                                <input type="email" class="form-control" id="shipping_email" name="shipping_email" 
                                       value="<?= sanitize($user['email'] ?? '') ?>">
                            </div>
                            
                            <div class="col-md-6">
                                <label for="shipping_city" class="form-label">শহর <span class="text-danger">*</span></label>
                                <select class="form-select" id="shipping_city" name="shipping_city" required>
                                    <option value="">শহর নির্বাচন করুন</option>
                                    <option value="Dhaka" <?= ($user['city'] ?? '') === 'Dhaka' ? 'selected' : '' ?>>ঢাকা</option>
                                    <option value="Chattogram" <?= ($user['city'] ?? '') === 'Chattogram' ? 'selected' : '' ?>>চট্টগ্রাম</option>
                                    <option value="Sylhet" <?= ($user['city'] ?? '') === 'Sylhet' ? 'selected' : '' ?>>সিলেট</option>
                                    <option value="Rajshahi" <?= ($user['city'] ?? '') === 'Rajshahi' ? 'selected' : '' ?>>রাজশাহী</option>
                                    <option value="Khulna" <?= ($user['city'] ?? '') === 'Khulna' ? 'selected' : '' ?>>খুলনা</option>
                                    <option value="Barishal" <?= ($user['city'] ?? '') === 'Barishal' ? 'selected' : '' ?>>বরিশাল</option>
                                    <option value="Rangpur" <?= ($user['city'] ?? '') === 'Rangpur' ? 'selected' : '' ?>>রংপুর</option>
                                    <option value="Mymensingh" <?= ($user['city'] ?? '') === 'Mymensingh' ? 'selected' : '' ?>>ময়মনসিংহ</option>
                                    <option value="Other">অন্যান্য</option>
                                </select>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="shipping_area" class="form-label">এলাকা</label>
                                <input type="text" class="form-control" id="shipping_area" name="shipping_area" 
                                       placeholder="থানা / এলাকার নাম">
                            </div>
                            
                            <div class="col-12">
                                <label for="shipping_address" class="form-label">সম্পূর্ণ ঠিকানা <span class="text-danger">*</span></label>
                                <textarea class="form-control" id="shipping_address" name="shipping_address" rows="2" 
                                          placeholder="বাড়ি নং, রোড নং, এলাকা" required><?= sanitize($user['address'] ?? '') ?></textarea>
                            </div>
                            
                            <div class="col-12">
                                <label for="notes" class="form-label">অর্ডার নোট (ঐচ্ছিক)</label>
                                <textarea class="form-control" id="notes" name="notes" rows="2" 
                                          placeholder="বিশেষ কোনো নির্দেশনা থাকলে লিখুন..."></textarea>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Payment Method Selection -->
                    <div class="checkout-section">
                        <h5><i class="bi bi-wallet2 me-2"></i>পেমেন্ট মেথড</h5>
                        
                        <div class="row g-3">
                            <!-- bKash -->
                            <div class="col-md-6">
                                <div class="payment-method-card" data-method="bKash" data-merchant="<?= BKASH_MERCHANT_NUMBER ?>">
                                    <div class="d-flex align-items-center">
                                        <span class="badge bg-danger px-3 py-3 fs-5">bKash</span>
                                        <div class="ms-3">
                                            <strong>bKash</strong>
                                            <small class="d-block text-muted">মোবাইল ব্যাংকিং</small>
                                        </div>
                                        <i class="bi bi-check-circle-fill text-success ms-auto d-none check-icon"></i>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Nagad -->
                            <div class="col-md-6">
                                <div class="payment-method-card" data-method="Nagad" data-merchant="<?= NAGAD_MERCHANT_NUMBER ?>">
                                    <div class="d-flex align-items-center">
                                        <span class="badge bg-warning text-dark px-3 py-3 fs-5">Nagad</span>
                                        <div class="ms-3">
                                            <strong>Nagad</strong>
                                            <small class="d-block text-muted">মোবাইল ব্যাংকিং</small>
                                        </div>
                                        <i class="bi bi-check-circle-fill text-success ms-auto d-none check-icon"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Payment Instructions (shown after selection) -->
                        <div id="payment-instructions" class="mt-4 p-3 bg-light rounded" style="display: none;">
                            <h6 class="text-primary"><i class="bi bi-info-circle me-2"></i>পেমেন্ট নির্দেশনা</h6>
                            <ol class="mb-3 small">
                                <li>আপনার bKash/Nagad অ্যাপ খুলুন</li>
                                <li>"Send Money" অপশনে যান</li>
                                <li>মার্চেন্ট নম্বর: <strong id="merchant-number" class="text-primary">-</strong></li>
                                <li>টোটাল অ্যামাউন্ট: <strong class="text-primary"><?= formatPrice($cartTotals['grand_total']) ?></strong> পাঠান</li>
                                <li>Transaction ID নিচে দিন</li>
                            </ol>
                            
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label for="sender_mobile" class="form-label">আপনার bKash/Nagad নম্বর <span class="text-danger">*</span></label>
                                    <input type="tel" class="form-control" id="sender_mobile" name="sender_mobile" 
                                           placeholder="01XXXXXXXXX" required>
                                    <small class="text-muted">যে নম্বর থেকে টাকা পাঠিয়েছেন</small>
                                </div>
                                
                                <div class="col-md-6">
                                    <label for="trx_id" class="form-label">Transaction ID <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="trx_id" name="trx_id" 
                                           placeholder="যেমন: 8N7A2K3M5P" required>
                                    <small class="text-muted">bKash/Nagad থেকে প্রাপ্ত TrxID</small>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                </div>
                
                <!-- Right Column: Order Summary -->
                <div class="col-lg-4">
                    <div class="order-summary">
                        <h5 class="mb-3"><i class="bi bi-receipt me-2"></i>অর্ডার সামারি</h5>
                        
                        <!-- Cart Items -->
                        <div class="order-items mb-3">
                            <?php foreach ($cartItems as $item): ?>
                            <div class="d-flex align-items-center mb-2 pb-2 border-bottom">
                                <img src="<?= $item['image'] ? UPLOADS_URL . '/products/' . $item['image'] : asset('img/no-image.png') ?>" 
                                     alt="<?= sanitize($item['name']) ?>" 
                                     class="rounded" width="50" height="50" style="object-fit: cover;">
                                <div class="ms-2 flex-grow-1">
                                    <small class="d-block fw-medium"><?= sanitize(truncate($item['name'], 30)) ?></small>
                                    <small class="text-muted"><?= $item['qty'] ?> × <?= formatPrice($item['unit_price']) ?></small>
                                </div>
                                <strong class="text-nowrap"><?= formatPrice($item['qty'] * $item['unit_price']) ?></strong>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        
                        <!-- Promo Code -->
                        <div class="mb-3">
                            <label class="form-label small">প্রোমো কোড</label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="promoCodeInput" placeholder="কোড লিখুন">
                                <button class="btn btn-outline-primary" type="button" id="applyPromoBtn">প্রয়োগ</button>
                            </div>
                            <div id="promoAppliedMsg" class="mt-2 small" style="display: none;"></div>
                        </div>
                        
                        <!-- Totals -->
                        <div class="summary-row">
                            <span>সাবটোটাল</span>
                            <span id="cart-subtotal"><?= formatPrice($cartTotals['subtotal']) ?></span>
                        </div>
                        
                        <div class="summary-row">
                            <span>ভ্যাট (<?= VAT_PERCENT ?>%)</span>
                            <span id="cart-vat"><?= formatPrice($cartTotals['vat_amount']) ?></span>
                        </div>
                        
                        <?php if ($cartTotals['tax_amount'] > 0): ?>
                        <div class="summary-row">
                            <span>ট্যাক্স</span>
                            <span id="cart-tax"><?= formatPrice($cartTotals['tax_amount']) ?></span>
                        </div>
                        <?php endif; ?>
                        
                        <div class="summary-row text-success">
                            <span>ছাড়</span>
                            <span id="cart-discount">- <?= formatPrice(0) ?></span>
                        </div>
                        
                        <div class="summary-row total">
                            <span>সর্বমোট</span>
                            <span id="cart-grand-total"><?= formatPrice($cartTotals['grand_total']) ?></span>
                        </div>
                        
                        <!-- Place Order Button -->
                        <button type="submit" class="btn btn-primary btn-lg w-100 mt-3">
                            <i class="bi bi-check-circle me-2"></i>অর্ডার সম্পন্ন করুন
                        </button>
                        
                        <p class="text-muted small text-center mt-3 mb-0">
                            <i class="bi bi-shield-check me-1"></i>
                            আপনার তথ্য সুরক্ষিত আছে
                        </p>
                    </div>
                </div>
            </div>
        </form>
    </div>
</main>

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

<script>
$(function() {
    // Payment method selection
    $('.payment-method-card').on('click', function() {
        $('.payment-method-card').removeClass('selected').find('.check-icon').addClass('d-none');
        $(this).addClass('selected').find('.check-icon').removeClass('d-none');
        
        var method = $(this).data('method');
        var merchant = $(this).data('merchant');
        
        $('#payment-method').val(method);
        $('#merchant-number').text(merchant);
        $('#payment-instructions').slideDown();
    });
    
    // Form submission
    $('#checkoutForm').on('submit', function(e) {
        e.preventDefault();
        
        var form = $(this);
        var btn = form.find('button[type="submit"]');
        var originalText = btn.html();
        
        // Validate payment method selected
        if (!$('#payment-method').val()) {
            Swal.fire('ত্রুটি!', 'পেমেন্ট মেথড নির্বাচন করুন', 'error');
            return false;
        }
        
        btn.html('<span class="spinner-border spinner-border-sm me-2"></span>অপেক্ষা করুন...').prop('disabled', true);
        
        $.post('<?= SITE_URL ?>/public/ajax/orders/place_order.php', form.serialize(), function(response) {
            if (response.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'সফল!',
                    text: response.message,
                    showConfirmButton: true,
                    confirmButtonText: 'ঠিক আছে'
                }).then(function() {
                    window.location.href = '<?= SITE_URL ?>/public/?page=order-success&order=' + response.data.order_no;
                });
            } else {
                Swal.fire('ত্রুটি!', response.message, 'error');
                if (response.errors) {
                    $.each(response.errors, function(field, msg) {
                        form.find('[name="' + field + '"]').addClass('is-invalid');
                    });
                }
            }
            btn.html(originalText).prop('disabled', false);
        }, 'json').fail(function(xhr) {
            Swal.fire('ত্রুটি!', 'সার্ভার সমস্যা: ' + xhr.responseText, 'error');
            btn.html(originalText).prop('disabled', false);
        });
        
        return false;
    });
});
</script>
