<?php
// =========================================================
// CHECKOUT PAGE - COMPLETE VERSION
// =========================================================
if (session_status() === PHP_SESSION_NONE) session_start();
require_once 'config.php';

// =========================================================
// CAPTURE AFFILIATE REF FROM URL
// =========================================================
if (isset($_GET['ref'])) {
    $ref_code = $_GET['ref'];
    $affiliate = $conn->query("SELECT id FROM affiliates WHERE referral_code = '$ref_code' AND status = 'active'")->fetch_assoc();
    if ($affiliate) {
        $_SESSION['affiliate_ref'] = $affiliate['id'];
        $_SESSION['affiliate_code'] = $ref_code;
        // Set cookie for 30 days
        setcookie('affiliate_ref', $ref_code, time() + (86400 * 30), '/');
    }
}

// Check cookie if no session
if (!isset($_SESSION['affiliate_ref']) && isset($_COOKIE['affiliate_ref'])) {
    $ref_code = $_COOKIE['affiliate_ref'];
    $affiliate = $conn->query("SELECT id FROM affiliates WHERE referral_code = '$ref_code' AND status = 'active'")->fetch_assoc();
    if ($affiliate) {
        $_SESSION['affiliate_ref'] = $affiliate['id'];
        $_SESSION['affiliate_code'] = $ref_code;
    }
}

// =========================================================
// REDIRECT IF CART IS EMPTY
// =========================================================
if (empty($_SESSION['cart'])) {
    header('Location: cart.php');
    exit;
}

// =========================================================
// CALCULATE TOTALS
// =========================================================
$cart = $_SESSION['cart'];
$subtotal = 0;
foreach ($cart as $id => $item) {
    $subtotal += $item['quantity'] * $item['price'];
}
$delivery = 50;
$total = $subtotal + $delivery;

// =========================================================
// GET BRAND INFO
// =========================================================
$brand = getBrand();
$whatsapp_number = $brand['whatsapp'] ?? '01775121112';

// =========================================================
// PROCESS ORDER SUBMISSION
// =========================================================
$orderPlaced = false;
$error_msg = '';
$order_number = '';
$payment_method = '';
$transaction_id = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Sanitize inputs
    $name = trim($_POST['name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $payment_method = $_POST['payment_method'] ?? 'cod';
    $transaction_id = trim($_POST['transaction_id'] ?? '');
    $notes = trim($_POST['notes'] ?? '');
    
    // Basic validation
    if (empty($name) || empty($phone)) {
        $error_msg = 'নাম এবং মোবাইল নম্বর আবশ্যক।';
    } else {
        // Generate unique order number
        $order_number = 'ORD' . date('Ymd') . rand(1000, 9999);
        $status = 'pending';
        $payment_status = ($payment_method == 'cod') ? 'unpaid' : 'unpaid';
        
        // Escape for database
        $name_esc = $conn->real_escape_string($name);
        $phone_esc = $conn->real_escape_string($phone);
        $email_esc = $conn->real_escape_string($email);
        $address_esc = $conn->real_escape_string($address);
        $payment_method_esc = $conn->real_escape_string($payment_method);
        $transaction_id_esc = $conn->real_escape_string($transaction_id);
        $notes_esc = $conn->real_escape_string($notes);
        
        // Insert order
        $insert = $conn->query("INSERT INTO orders 
            (order_number, customer_name, customer_phone, customer_email, customer_address, 
             total_amount, payment_method, transaction_id, status, payment_status, notes, created_at) 
            VALUES 
            ('$order_number', '$name_esc', '$phone_esc', '$email_esc', '$address_esc', 
             $total, '$payment_method_esc', '$transaction_id_esc', '$status', '$payment_status', '$notes_esc', NOW())");
        
        if ($insert) {
            $order_id = $conn->insert_id;
            
            // Insert order items
            foreach ($cart as $id => $item) {
                // Get product/service name from database
                if ($item['type'] == 'product') {
                    $prod = $conn->query("SELECT name FROM products WHERE id = $id")->fetch_assoc();
                    $prod_name = $prod ? $prod['name'] : 'Product #' . $id;
                } else {
                    $serv = $conn->query("SELECT title FROM services WHERE id = $id")->fetch_assoc();
                    $prod_name = $serv ? $serv['title'] : 'Service #' . $id;
                }
                $qty = (int)$item['quantity'];
                $price = (float)$item['price'];
                $conn->query("INSERT INTO order_items (order_id, product_id, product_name, quantity, price) 
                              VALUES ($order_id, $id, '$prod_name', $qty, $price)");
            }
            
            // =========================================================
            // AFFILIATE COMMISSION TRACKING
            // =========================================================
            if (isset($_SESSION['affiliate_ref'])) {
                $affiliate_id = $_SESSION['affiliate_ref'];
                $commission_rate = $conn->query("SELECT commission_rate FROM affiliates WHERE id = $affiliate_id")->fetch_assoc()['commission_rate'] ?? 10;
                $commission = ($total * $commission_rate) / 100;
                
                // Update the referral record with order info
                $conn->query("UPDATE affiliate_referrals 
                              SET order_id = $order_id, 
                                  commission_amount = $commission, 
                                  status = 'pending',
                                  referred_customer_email = '$email_esc',
                                  referred_customer_phone = '$phone_esc'
                              WHERE affiliate_id = $affiliate_id AND order_id IS NULL 
                              ORDER BY id DESC LIMIT 1");
                
                // Update affiliate balance and total earnings
                $conn->query("UPDATE affiliates 
                              SET balance = balance + $commission, 
                                  total_earnings = total_earnings + $commission 
                              WHERE id = $affiliate_id");
                
                // Update order with affiliate info
                $conn->query("UPDATE orders 
                              SET affiliate_id = $affiliate_id, 
                                  referral_code = '{$_SESSION['affiliate_code']}' 
                              WHERE id = $order_id");
                
                unset($_SESSION['affiliate_ref'], $_SESSION['affiliate_code']);
            }
            
            // =========================================================
            // SEND SMS TO ADMIN (if transaction ID provided)
            // =========================================================
            if (!empty($transaction_id) && $payment_method != 'cod') {
                $admin_phone = '01681519799';
                $admin_msg = "🔔 New Payment Received!\n\nOrder: $order_number\nAmount: ৳" . number_format($total, 2) . "\nMethod: $payment_method\nTxn ID: $transaction_id\nCustomer: $name ($phone)\n\nPlease verify and confirm.";
                if (function_exists('sendSMSViaBulkSMSBD')) {
                    sendSMSViaBulkSMSBD($admin_phone, $admin_msg);
                }
            }
            
            // =========================================================
            // SEND CONFIRMATION SMS TO CUSTOMER
            // =========================================================
            if (function_exists('sendSMSViaBulkSMSBD')) {
                $customer_msg = "Dear $name, Your order #$order_number has been placed successfully. Total: ৳" . number_format($total, 2) . ". Thank you - Dr. Ferdous";
                sendSMSViaBulkSMSBD($phone, $customer_msg);
            }
            
            // Clear cart
            unset($_SESSION['cart']);
            $orderPlaced = true;
            
        } else {
            $error_msg = 'অর্ডার সংরক্ষণ করতে সমস্যা হয়েছে। আবার চেষ্টা করুন।';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>চেকআউট | <?= htmlspecialchars($brand['name'] ?? 'ওয়ান হোমিওপ্যাথি') ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { background: #f0f2f5; font-family: 'Hind Siliguri', sans-serif; }
        .checkout-header { background: linear-gradient(135deg, #2d6a4f, #1b4332); color: #fff; padding: 80px 0 40px; margin-bottom: 40px; text-align: center; }
        .form-card, .order-summary { background: #fff; border-radius: 20px; padding: 25px; box-shadow: 0 5px 15px rgba(0,0,0,0.08); margin-bottom: 20px; }
        .btn-place-order { background: #2d6a4f; color: #fff; border-radius: 50px; padding: 12px; font-weight: bold; width: 100%; border: none; transition: all 0.3s; }
        .btn-place-order:hover { background: #1b4332; transform: translateY(-2px); box-shadow: 0 5px 15px rgba(45,106,79,0.3); }
        footer { background: #0a0a0a; color: #aaa; padding: 30px 0 20px; margin-top: 50px; text-align: center; }
        .alert { border-radius: 15px; }
        .back-to-cart { background: #6c757d; color: #fff; border-radius: 50px; padding: 10px 20px; text-decoration: none; display: inline-block; transition: 0.3s; }
        .back-to-cart:hover { transform: translateY(-2px); color: #fff; }
    </style>
</head>
<body>

<!-- Simple Navbar -->
<nav class="navbar navbar-expand-lg bg-dark fixed-top">
    <div class="container">
        <a class="navbar-brand text-white" href="index.php"><i class="fas fa-clinic-medical"></i> <?= htmlspecialchars($brand['name'] ?? 'ওয়ান হোমিওপ্যাথি') ?></a>
        <a href="cart.php" class="back-to-cart"><i class="fas fa-arrow-left"></i> কার্টে ফিরুন</a>
    </div>
</nav>

<div class="checkout-header">
    <div class="container">
        <h1><i class="fas fa-credit-card"></i> চেকআউট</h1>
        <p>আপনার অর্ডার সম্পন্ন করতে নিচের তথ্য পূরণ করুন</p>
    </div>
</div>

<div class="container">
    <?php if ($orderPlaced): ?>
        <div class="alert alert-success text-center">
            <i class="fas fa-check-circle fa-2x mb-2"></i>
            <h4>অর্ডার সফল হয়েছে!</h4>
            <p>আপনার অর্ডার নম্বর: <strong><?= $order_number ?></strong></p>
            <?php if (!empty($transaction_id) && $payment_method != 'cod'): ?>
                <p>আমরা আপনার ট্রানজেকশন আইডি পেয়েছি। প্রশাসক শীঘ্রই যাচাই করবেন এবং নিশ্চিত করবেন।</p>
            <?php else: ?>
                <p>আপনার অর্ডার গ্রহণ করা হয়েছে। আমরা শীঘ্রই আপনার সাথে যোগাযোগ করব।</p>
            <?php endif; ?>
            <div class="mt-3">
                <a href="index.php" class="btn btn-primary btn-lg"><i class="fas fa-home"></i> হোমপেজে ফিরুন</a>
                <a href="opd/dashboard.php?tab=orders" class="btn btn-outline-primary btn-lg"><i class="fas fa-box"></i> আমার অর্ডার</a>
            </div>
        </div>
    <?php elseif ($error_msg): ?>
        <div class="alert alert-danger text-center">
            <i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($error_msg) ?>
            <br><a href="javascript:history.back()" class="btn btn-sm btn-outline-danger mt-2"><i class="fas fa-arrow-left"></i> পেছনে যান</a>
        </div>
    <?php else: ?>
    <div class="row">
        <div class="col-lg-7">
            <div class="form-card">
                <h4><i class="fas fa-user-circle"></i> বিলিং তথ্য</h4>
                <form method="post" id="checkoutForm">
                    <div class="mb-3">
                        <label class="form-label">আপনার নাম <span class="text-danger">*</span></label>
                        <input type="text" name="name" class="form-control" placeholder="আপনার পুরো নাম" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">মোবাইল নম্বর <span class="text-danger">*</span></label>
                        <input type="tel" name="phone" class="form-control" placeholder="০১৭xxxxxxxx" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">ইমেইল (ঐচ্ছিক)</label>
                        <input type="email" name="email" class="form-control" placeholder="your@email.com">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">ঠিকানা (ঐচ্ছিক)</label>
                        <textarea name="address" class="form-control" rows="3" placeholder="আপনার সম্পূর্ণ ঠিকানা"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">অর্ডার নোট (ঐচ্ছিক)</label>
                        <textarea name="notes" class="form-control" rows="2" placeholder="কোন বিশেষ নির্দেশনা?"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">পেমেন্ট পদ্ধতি <span class="text-danger">*</span></label>
                        <select name="payment_method" id="paymentMethod" class="form-select" required>
                            <option value="bkash">bKash</option>
                            <option value="nagad">Nagad</option>
                            <option value="rocket">Rocket</option>
                            <option value="cod">ক্যাশ অন ডেলিভারি (COD)</option>
                        </select>
                    </div>
                    <div id="transactionField" class="mb-3">
                        <label class="form-label">ট্রানজেকশন আইডি</label>
                        <input type="text" name="transaction_id" class="form-control" placeholder="bKash/Nagad/Rocket ট্রানজেকশন আইডি">
                        <small class="text-muted">bKash/Nagad/Rocket এর মাধ্যমে পেমেন্ট করলে ট্রানজেকশন আইডি দিন।</small>
                    </div>
                    <button type="submit" class="btn-place-order"><i class="fas fa-check-circle"></i> অর্ডার কনফার্ম করুন</button>
                </form>
            </div>
        </div>
        <div class="col-lg-5">
            <div class="order-summary">
                <h5><i class="fas fa-shopping-bag"></i> অর্ডার সামারি</h5>
                <hr>
                <div class="d-flex justify-content-between mb-2">
                    <span>পণ্যের মূল্য:</span>
                    <span>৳<?= number_format($subtotal, 2) ?></span>
                </div>
                <div class="d-flex justify-content-between mb-2">
                    <span>ডেলিভারি চার্জ:</span>
                    <span>৳50.00</span>
                </div>
                <?php if (isset($_SESSION['affiliate_ref'])): ?>
                <div class="d-flex justify-content-between mb-2 text-success">
                    <span><i class="fas fa-handshake"></i> Affiliate Order</span>
                    <span>✅ Referral Tracked</span>
                </div>
                <?php endif; ?>
                <hr>
                <div class="d-flex justify-content-between fw-bold">
                    <span>মোট:</span>
                    <span>৳<?= number_format($total, 2) ?></span>
                </div>
                <hr>
                <div class="alert alert-info small">
                    <i class="fas fa-info-circle"></i> অর্ডার কনফার্ম করার পর আমরা আপনার মোবাইলে একটি কনফার্মেশন এসএমএস পাঠাব।
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

<footer>
    <div class="container">
        <p>&copy; <?= date('Y') ?> <?= htmlspecialchars($brand['name'] ?? 'ওয়ান হোমিওপ্যাথি') ?>। সর্বস্বত্ব সংরক্ষিত।</p>
        <p><a href="affiliate/register.php" class="text-light"><i class="fas fa-handshake"></i> Become an Affiliate</a></p>
    </div>
</footer>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
$(document).ready(function() {
    // Toggle transaction ID field based on payment method
    $('#paymentMethod').change(function() {
        if ($(this).val() == 'cod') {
            $('#transactionField').slideUp();
            $('input[name="transaction_id"]').removeAttr('required');
        } else {
            $('#transactionField').slideDown();
            $('input[name="transaction_id"]').attr('required', true);
        }
    }).trigger('change');
    
    // Form validation before submit
    $('#checkoutForm').submit(function(e) {
        const paymentMethod = $('#paymentMethod').val();
        const transactionId = $('input[name="transaction_id"]').val().trim();
        
        if (paymentMethod != 'cod' && !transactionId) {
            e.preventDefault();
            alert('দয়া করে ট্রানজেকশন আইডি দিন।');
            $('input[name="transaction_id"]').focus();
            return false;
        }
        return true;
    });
});
</script>

<style>
@media (max-width: 768px) {
    .checkout-header { padding: 60px 0 30px; }
    .checkout-header h1 { font-size: 1.5rem; }
    .btn-place-order { font-size: 1rem; }
}
</style>
</body>
</html>