<?php
session_start();
require_once 'config.php';

if (empty($_SESSION['cart'])) {
    header('Location: cart.php');
    exit;
}

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

$orderPlaced = false;
$error_msg = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $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'] ?? '');
    
    if (empty($name) || empty($phone)) {
        $error_msg = 'নাম এবং মোবাইল নম্বর আবশ্যক।';
    } else {
        $order_number = 'ORD' . date('Ymd') . rand(1000, 9999);
        $status = 'pending';
        $payment_status = ($payment_method == 'cod') ? 'unpaid' : 'unpaid'; // will be updated after verification
        
        $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);
        
        $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, created_at) 
            VALUES 
            ('$order_number', '$name_esc', '$phone_esc', '$email_esc', '$address_esc', $total, '$payment_method_esc', '$transaction_id_esc', '$status', '$payment_status', NOW())");
        
        if ($insert) {
            $order_id = $conn->insert_id;
            
            foreach ($cart as $id => $item) {
                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)");
            }
            
            // ============================================
            // 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);
                }
            }
            
            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; }
        .btn-place-order:hover { background: #1b4332; }
        footer { background: #0a0a0a; color: #aaa; padding: 30px 0 20px; margin-top: 50px; text-align: center; }
    </style>
</head>
<body>

<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="btn btn-warning"><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; ?>
            <a href="index.php" class="btn btn-primary mt-2">হোমপেজে ফিরুন</a>
        </div>
    <?php elseif ($error_msg): ?>
        <div class="alert alert-danger text-center">
            <i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($error_msg) ?>
        </div>
    <?php else: ?>
    <div class="row">
        <div class="col-lg-7">
            <div class="form-card">
                <h4>বিলিং তথ্য</h4>
                <form method="post" id="checkoutForm">
                    <div class="mb-3">
                        <label class="form-label">আপনার নাম *</label>
                        <input type="text" name="name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">মোবাইল নম্বর *</label>
                        <input type="tel" name="phone" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">ইমেইল (ঐচ্ছিক)</label>
                        <input type="email" name="email" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">ঠিকানা (ঐচ্ছিক)</label>
                        <textarea name="address" class="form-control" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">পেমেন্ট পদ্ধতি *</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 ট্রানজেকশন আইডি">
                    </div>
                    <button type="submit" class="btn-place-order">অর্ডার কনফার্ম করুন</button>
                </form>
            </div>
        </div>
        <div class="col-lg-5">
            <div class="order-summary">
                <h5>অর্ডার সামারি</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>
                <hr>
                <div class="d-flex justify-content-between fw-bold">
                    <span>মোট:</span>
                    <span>৳<?= number_format($total, 2) ?></span>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

<footer>
    <div class="container">
        <p>&copy; <?= date('Y') ?> <?= htmlspecialchars($brand['name'] ?? 'ওয়ান হোমিওপ্যাথি') ?>। সর্বস্বত্ব সংরক্ষিত।</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>
    $('#paymentMethod').change(function() {
        if ($(this).val() == 'cod') {
            $('#transactionField').hide();
            $('input[name="transaction_id"]').removeAttr('required');
        } else {
            $('#transactionField').show();
            $('input[name="transaction_id"]').attr('required', true);
        }
    }).trigger('change');
</script>
</body>
</html>