<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once 'includes/db.php';

// যদি কার্ট ফাঁকা থাকে এবং এটি সাকসেস পেজ না হয়, তবে কার্টে ফেরত পাঠাবে
if (empty($_SESSION['cart']) && !isset($_GET['success'])) {
    header("Location: cart.php");
    exit;
}

// কার্টের সাবটোটাল হিসাব
$cart_items = isset($_SESSION['cart']) ? $_SESSION['cart'] :[];
$subtotal = 0;
foreach ($cart_items as $item) {
    $subtotal += $item['price'] * $item['quantity'];
}

// লগইন করা কাস্টমারের তথ্য সংগ্রহ (অটো-ফিল করার জন্য)
$user_id = $_SESSION['customer_id'] ?? null; // ইউজার আইডি (লগইন না থাকলে NULL)
$logged_in_name = $_SESSION['customer_name'] ?? '';
$logged_in_phone = $_SESSION['customer_phone'] ?? '';
$logged_in_address = $_SESSION['customer_address'] ?? '';

// ফর্ম সাবমিট হলে অর্ডার সেভ করার লজিক
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['place_order'])) {
    $name = trim($_POST['name']);
    $phone = trim($_POST['phone']);
    $address = trim($_POST['address']);
    $area = $_POST['delivery_area'] ?? 'dhaka';
    $note = trim($_POST['note']);

    // এরিয়া অনুযায়ী ডেলিভারি চার্জ নির্ধারণ
    $delivery_charge = ($area === 'outside') ? 120 : 70;
    $final_total = $subtotal + $delivery_charge;

    if (empty($name) || empty($phone) || empty($address)) {
        $error = "অনুগ্রহ করে নাম, ফোন নাম্বার এবং ঠিকানা সঠিকভাবে পূরণ করুন।";
    } else {
        try {
            $pdo->beginTransaction();
            $order_number = 'ORD-' . strtoupper(substr(uniqid(), -6));

            // ১. orders টেবিলে সেভ (নতুন user_id কলামসহ)
            $stmt = $pdo->prepare("INSERT INTO orders (user_id, order_number, customer_name, customer_phone, customer_address, total_amount, order_note, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'Pending')");
            $stmt->execute([$user_id, $order_number, $name, $phone, $address, $final_total, $note]);
            $order_id = $pdo->lastInsertId();

            // ২. order_items টেবিলে সেভ
            $stmt_items = $pdo->prepare("INSERT INTO order_items (order_id, product_id, quantity, unit_price, selected_options, file_path) VALUES (?, ?, ?, ?, ?, ?)");
            foreach ($cart_items as $item) {
                $options_json = !empty($item['options']) ? json_encode($item['options'], JSON_UNESCAPED_UNICODE) : null;
                $stmt_items->execute([$order_id, $item['product_id'], $item['quantity'], $item['price'], $options_json, $item['design_file']]);
            }

            $pdo->commit();
            unset($_SESSION['cart']);
            header("Location: checkout.php?success=1&order_no=" . $order_number);
            exit;

        } catch (Exception $e) {
            $pdo->rollBack();
            $error = "অর্ডার সম্পূর্ণ করতে সমস্যা হয়েছে: " . $e->getMessage();
        }
    }
}

require_once 'includes/header.php';
?>

<!-- Breadcrumb -->
<div class="bg-gray-100 py-3 border-b border-gray-200">
    <div class="container mx-auto px-4 text-sm font-bangla text-gray-600">
        <a href="index.php" class="hover:text-primary">হোম</a> / 
        <a href="cart.php" class="hover:text-primary">কার্ট</a> / 
        <span class="text-primary font-bold">চেকআউট</span>
    </div>
</div>

<section class="py-10 bg-gray-50 min-h-[60vh] pb-24">
    <div class="container mx-auto px-4">

        <?php if (isset($_GET['success'])): ?>
            <!-- Success Message -->
            <div class="max-w-xl mx-auto bg-white p-10 rounded-2xl shadow-sm text-center border border-green-100">
                <div class="w-20 h-20 mx-auto bg-green-100 text-green-500 rounded-full flex items-center justify-center text-4xl mb-6"><i class="fa-solid fa-check"></i></div>
                <h1 class="text-2xl font-bold font-bangla mb-2">অর্ডার সফল হয়েছে!</h1>
                <p class="text-gray-500 font-bangla mb-6">আমাদের প্রতিনিধি আপনার সাথে যোগাযোগ করবেন। আপনার অর্ডার নাম্বার: <br><span class="text-xl font-bold text-primary en-font">#<?= htmlspecialchars($_GET['order_no']) ?></span></p>
                
                <?php if($user_id): ?>
                    <a href="profile.php" class="bg-blue-600 text-white px-8 py-3 rounded-full font-bold font-bangla mr-2 hover:bg-blue-700 transition">অর্ডার লিস্ট দেখুন</a>
                <?php endif; ?>
                <a href="index.php" class="bg-primary text-white px-8 py-3 rounded-full font-bold font-bangla hover:bg-blue-900 transition">হোমপেজে ফিরে যান</a>
            </div>

        <?php else: ?>
            <div class="flex flex-col md:flex-row justify-between md:items-center mb-8 gap-4">
                <h1 class="text-2xl md:text-3xl font-bold font-bangla">অর্ডার <span class="text-primary">কনফার্ম করুন</span></h1>
                
                <?php if(!$user_id): ?>
                    <p class="text-sm font-bangla text-gray-600 bg-blue-50 px-4 py-2 rounded-lg border border-blue-100">
                        একাউন্ট আছে? <a href="login.php" class="font-bold text-primary hover:underline">লগইন করুন</a> (অটো-ফিল এর জন্য)
                    </p>
                <?php endif; ?>
            </div>

            <?php if ($error): ?>
                <div class="bg-red-50 text-red-600 p-4 rounded-lg mb-6 font-bangla border border-red-200">
                    <i class="fa-solid fa-circle-exclamation mr-2"></i> <?= $error ?>
                </div>
            <?php endif; ?>

            <div class="grid grid-cols-1 lg:grid-cols-12 gap-8">
                
                <!-- Form Area -->
                <div class="lg:col-span-7">
                    <div class="bg-white p-6 rounded-xl shadow-sm border border-gray-100">
                        <form id="checkoutForm" action="checkout.php" method="POST" class="space-y-5">
                            <input type="hidden" name="place_order" value="1">
                            
                            <h3 class="text-lg font-bold font-bangla border-b pb-3 mb-4"><i class="fa-regular fa-address-card text-primary mr-2"></i> ডেলিভারি তথ্য</h3>
                            
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-bold mb-1 font-bangla">আপনার নাম *</label>
                                    <input type="text" name="name" value="<?= htmlspecialchars($logged_in_name) ?>" required class="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary outline-none font-bangla">
                                </div>
                                <div>
                                    <label class="block text-sm font-bold mb-1 font-bangla">মোবাইল নাম্বার *</label>
                                    <input type="text" name="phone" value="<?= htmlspecialchars($logged_in_phone) ?>" required class="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary outline-none en-font">
                                </div>
                            </div>

                            <div class="bg-blue-50 p-4 rounded-xl border border-blue-100">
                                <label class="block text-sm font-bold mb-3 font-bangla">ডেলিভারি এরিয়া সিলেক্ট করুন *</label>
                                <div class="grid grid-cols-2 gap-4">
                                    <label class="flex items-center gap-3 bg-white p-3 rounded-lg border border-gray-200 cursor-pointer hover:border-primary transition">
                                        <input type="radio" name="delivery_area" value="dhaka" checked onchange="updateTotal(70)" class="w-4 h-4 text-primary">
                                        <div class="font-bangla text-sm">
                                            <p class="font-bold">ঢাকার ভেতরে</p>
                                            <p class="text-xs text-gray-500 en-font">৳ 70</p>
                                        </div>
                                    </label>
                                    <label class="flex items-center gap-3 bg-white p-3 rounded-lg border border-gray-200 cursor-pointer hover:border-primary transition">
                                        <input type="radio" name="delivery_area" value="outside" onchange="updateTotal(120)" class="w-4 h-4 text-primary">
                                        <div class="font-bangla text-sm">
                                            <p class="font-bold">ঢাকার বাইরে</p>
                                            <p class="text-xs text-gray-500 en-font">৳ 120</p>
                                        </div>
                                    </label>
                                </div>
                            </div>

                            <div>
                                <label class="block text-sm font-bold mb-1 font-bangla">বিস্তারিত ঠিকানা *</label>
                                <textarea name="address" required rows="3" class="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary outline-none font-bangla"><?= htmlspecialchars($logged_in_address) ?></textarea>
                            </div>

                            <div>
                                <label class="block text-sm font-bold mb-1 font-bangla">অর্ডার নোট (অপশনাল)</label>
                                <textarea name="note" rows="2" class="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary outline-none font-bangla"></textarea>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Summary Area -->
                <div class="lg:col-span-5">
                    <div class="bg-white p-6 rounded-xl shadow-sm border border-primary border-opacity-20 sticky top-24">
                        <h3 class="text-lg font-bold font-bangla border-b pb-3 mb-4">অর্ডার সামারি</h3>
                        
                        <div class="space-y-3 mb-6">
                            <?php foreach ($cart_items as $item): ?>
                            <div class="flex justify-between text-sm">
                                <span class="font-bangla text-gray-600"><?= htmlspecialchars($item['name']) ?> (x<?= $item['quantity'] ?>)</span>
                                <span class="en-font font-bold">৳<?= number_format($item['price'] * $item['quantity'], 2) ?></span>
                            </div>
                            <?php endforeach; ?>
                        </div>

                        <div class="bg-gray-50 p-4 rounded-lg space-y-3 mb-6 font-bangla">
                            <div class="flex justify-between text-sm">
                                <span>সাবটোটাল:</span>
                                <span class="en-font font-bold">৳<?= number_format($subtotal, 2) ?></span>
                            </div>
                            <div class="flex justify-between text-sm text-red-600">
                                <span>ডেলিভারি চার্জ:</span>
                                <span class="en-font font-bold">+ ৳ <span id="display_delivery">70</span></span>
                            </div>
                            <div class="border-t border-gray-200 pt-3 flex justify-between text-lg font-bold text-primary">
                                <span>সর্বমোট:</span>
                                <span class="en-font">৳ <span id="display_total"><?= number_format($subtotal + 70, 2) ?></span></span>
                            </div>
                        </div>

                        <button type="button" onclick="document.getElementById('checkoutForm').submit();" class="w-full bg-secondary text-white py-4 rounded-xl font-bold shadow-lg hover:bg-yellow-600 transition font-bangla">অর্ডার কনফার্ম করুন</button>
                    </div>
                </div>

            </div>
        <?php endif; ?>
    </div>
</section>

<script>
    const subtotal = <?= $subtotal ?>;
    function updateTotal(charge) {
        document.getElementById('display_delivery').innerText = charge;
        let total = subtotal + charge;
        document.getElementById('display_total').innerText = total.toLocaleString(undefined, {minimumFractionDigits: 2});
    }
</script>

<?php require_once 'includes/footer.php'; ?>