<?php
require_once 'includes/header.php';
require_once 'includes/sidebar.php';

$order_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$message = '';
$error = '';

// ১. স্ট্যাটাস আপডেট লজিক (এই পেজ থেকেও আপডেট করা যাবে)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $new_status = $_POST['status'];
    $allowed_statuses =['Pending', 'Processing', 'Completed', 'Cancelled'];
    
    if (in_array($new_status, $allowed_statuses)) {
        try {
            $stmt = $pdo->prepare("UPDATE orders SET status = ? WHERE id = ?");
            $stmt->execute([$new_status, $order_id]);
            $message = "অর্ডার স্ট্যাটাস আপডেট হয়েছে!";
        } catch (PDOException $e) {
            $error = "আপডেট ফেইল: " . $e->getMessage();
        }
    }
}

// ২. অর্ডার ইনফরমেশন আনা
try {
    $stmt = $pdo->prepare("SELECT * FROM orders WHERE id = ?");
    $stmt->execute([$order_id]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$order) {
        echo "<script>window.location.href = 'manage-orders.php';</script>";
        exit;
    }

    // ৩. অর্ডারের প্রোডাক্টগুলো (Items) আনা
    $stmt_items = $pdo->prepare("
        SELECT oi.*, p.name as product_name, p.image 
        FROM order_items oi 
        LEFT JOIN products p ON oi.product_id = p.id 
        WHERE oi.order_id = ?
    ");
    $stmt_items->execute([$order_id]);
    $order_items = $stmt_items->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    die("Error: " . $e->getMessage());
}

// স্ট্যাটাস কালার
function getStatusBadge($status) {
    switch ($status) {
        case 'Pending': return '<span class="bg-red-100 text-red-600 px-3 py-1 rounded-full text-sm font-bold">পেন্ডিং (Pending)</span>';
        case 'Processing': return '<span class="bg-blue-100 text-blue-600 px-3 py-1 rounded-full text-sm font-bold">প্রসেসিং (Processing)</span>';
        case 'Completed': return '<span class="bg-green-100 text-green-600 px-3 py-1 rounded-full text-sm font-bold">ডেলিভারড (Completed)</span>';
        case 'Cancelled': return '<span class="bg-gray-100 text-gray-600 px-3 py-1 rounded-full text-sm font-bold">ক্যানসেলড (Cancelled)</span>';
    }
}
?>

<div class="mb-6 flex flex-col md:flex-row md:items-center justify-between gap-4">
    <div class="flex items-center gap-3">
        <a href="manage-orders.php" class="w-10 h-10 bg-white border border-gray-200 rounded-full flex items-center justify-center text-gray-600 hover:bg-gray-50 transition shadow-sm">
            <i class="fa-solid fa-arrow-left"></i>
        </a>
        <div>
            <h1 class="text-2xl font-bold text-gray-800 font-bangla">অর্ডার ডিটেইলস</h1>
            <p class="text-sm text-gray-500 en-font">#<?= htmlspecialchars($order['order_number']) ?></p>
        </div>
    </div>
    
    <div class="flex items-center gap-3">
        <?= getStatusBadge($order['status']) ?>
    </div>
</div>

<?php if ($message): ?>
    <div class="bg-green-100 text-green-700 p-4 rounded-lg mb-6 font-bangla border border-green-200">
        <i class="fa-solid fa-circle-check mr-2"></i><?= $message ?>
    </div>
<?php endif; ?>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
    
    <!-- Left Column: Order Items -->
    <div class="lg:col-span-2 space-y-6">
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
            <div class="p-5 border-b border-gray-100 bg-slate-50 flex justify-between items-center">
                <h3 class="font-bold text-gray-800 font-bangla"><i class="fa-solid fa-box-open mr-2 text-primary"></i> অর্ডারকৃত প্রোডাক্টস</h3>
                <span class="text-xs bg-gray-200 text-gray-600 px-2 py-1 rounded font-bold en-font"><?= count($order_items) ?> Items</span>
            </div>
            
            <div class="p-5 space-y-6">
                <?php foreach ($order_items as $item): ?>
                    <div class="flex flex-col md:flex-row gap-5 pb-6 border-b border-gray-100 last:border-0 last:pb-0">
                        <!-- Product Image -->
                        <div class="w-20 h-20 md:w-24 md:h-24 bg-gray-50 rounded-lg flex-shrink-0 flex items-center justify-center border border-gray-200 overflow-hidden">
                            <?php if (!empty($item['image'])): ?>
                                <img src="../uploads/products/<?= htmlspecialchars($item['image']) ?>" class="w-full h-full object-cover">
                            <?php else: ?>
                                <i class="fa-solid fa-image text-gray-300 text-3xl"></i>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Product Info & Options -->
                        <div class="flex-grow">
                            <h4 class="font-bold text-gray-800 font-bangla text-lg mb-1"><?= htmlspecialchars($item['product_name']) ?></h4>
                            <div class="text-sm font-bold text-primary en-font mb-3">
                                ৳ <?= number_format($item['unit_price'], 2) ?> <span class="text-gray-400 text-xs font-normal">x <?= $item['quantity'] ?></span> = ৳ <?= number_format($item['unit_price'] * $item['quantity'], 2) ?>
                            </div>

                            <!-- Selected Options from Customer -->
                            <?php 
                                $selected_options = !empty($item['selected_options']) ? json_decode($item['selected_options'], true) :[];
                                if (!empty($selected_options)): 
                            ?>
                                <div class="bg-blue-50/50 border border-blue-100 rounded-lg p-3 mb-3">
                                    <p class="text-[10px] font-bold text-blue-600 uppercase tracking-wider mb-2 font-bangla">কাস্টমারের নির্বাচন:</p>
                                    <div class="flex flex-wrap gap-2">
                                        <?php foreach ($selected_options as $opt_name => $opt_val): ?>
                                            <span class="bg-white border border-blue-200 text-gray-700 text-xs px-2 py-1 rounded font-bangla shadow-sm">
                                                <strong class="text-gray-900"><?= htmlspecialchars($opt_name) ?>:</strong> <?= htmlspecialchars($opt_val) ?>
                                            </span>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            <?php endif; ?>

                            <!-- Uploaded Design File Link -->
                            <?php if (!empty($item['file_path'])): ?>
                                <a href="../uploads/designs/<?= htmlspecialchars($item['file_path']) ?>" download class="inline-flex items-center gap-2 bg-green-50 border border-green-200 text-green-700 hover:bg-green-600 hover:text-white px-4 py-2 rounded-lg text-sm font-bangla transition shadow-sm font-bold">
                                    <i class="fa-solid fa-download"></i> কাস্টমারের ডিজাইন ডাউনলোড করুন
                                </a>
                            <?php else: ?>
                                <span class="inline-flex items-center gap-2 bg-gray-50 border border-gray-200 text-gray-500 px-3 py-1.5 rounded text-xs font-bangla">
                                    <i class="fa-solid fa-ban"></i> কোনো ফাইল আপলোড করেনি
                                </span>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- Right Column: Customer Info & Action -->
    <div class="lg:col-span-1 space-y-6">
        
        <!-- Status Update Box -->
        <div class="bg-white rounded-xl shadow-sm border border-primary border-opacity-20 p-5 relative overflow-hidden">
            <div class="absolute top-0 right-0 w-16 h-16 bg-blue-50 rounded-bl-full -z-0"></div>
            <h3 class="font-bold text-gray-800 font-bangla mb-4 relative z-10"><i class="fa-solid fa-rotate mr-2 text-primary"></i> স্ট্যাটাস পরিবর্তন</h3>
            
            <form action="order-details.php?id=<?= $order_id ?>" method="POST" class="relative z-10">
                <select name="status" class="w-full bg-gray-50 border border-gray-300 rounded-lg px-4 py-2.5 outline-none focus:border-primary font-bangla mb-3">
                    <option value="Pending" <?= $order['status']=='Pending'?'selected':'' ?>>পেন্ডিং (Pending)</option>
                    <option value="Processing" <?= $order['status']=='Processing'?'selected':'' ?>>প্রসেসিং (Processing)</option>
                    <option value="Completed" <?= $order['status']=='Completed'?'selected':'' ?>>ডেলিভারড (Completed)</option>
                    <option value="Cancelled" <?= $order['status']=='Cancelled'?'selected':'' ?>>ক্যানসেলড (Cancelled)</option>
                </select>
                <input type="hidden" name="update_status" value="1">
                <button type="submit" class="w-full bg-primary text-white py-2.5 rounded-lg font-bold hover:bg-blue-800 transition font-bangla">আপডেট করুন</button>
            </form>
        </div>

        <!-- Customer Info -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5">
            <h3 class="font-bold text-gray-800 font-bangla mb-4 border-b pb-2"><i class="fa-solid fa-user text-primary mr-2"></i> কাস্টমার তথ্য</h3>
            
            <div class="space-y-4 font-bangla text-sm">
                <div>
                    <p class="text-gray-400 text-xs">নাম</p>
                    <p class="font-bold text-gray-800 text-base"><?= htmlspecialchars($order['customer_name']) ?></p>
                </div>
                <div>
                    <p class="text-gray-400 text-xs">মোবাইল নাম্বার</p>
                    <a href="tel:<?= htmlspecialchars($order['customer_phone']) ?>" class="font-bold text-primary en-font flex items-center gap-2 hover:underline">
                        <i class="fa-solid fa-phone-volume"></i> <?= htmlspecialchars($order['customer_phone']) ?>
                    </a>
                </div>
                <div>
                    <p class="text-gray-400 text-xs">ডেলিভারি ঠিকানা</p>
                    <p class="text-gray-700 bg-gray-50 p-3 rounded border border-gray-100 mt-1 leading-relaxed">
                        <?= nl2br(htmlspecialchars($order['customer_address'])) ?>
                    </p>
                </div>
                <?php if (!empty($order['order_note'])): ?>
                <div>
                    <p class="text-red-400 text-xs font-bold mb-1"><i class="fa-solid fa-note-sticky"></i> কাস্টমারের বিশেষ নোট:</p>
                    <p class="text-red-700 bg-red-50 p-3 rounded border border-red-100 italic">
                        <?= nl2br(htmlspecialchars($order['order_note'])) ?>
                    </p>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Order Summary -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5">
            <h3 class="font-bold text-gray-800 font-bangla mb-4 border-b pb-2"><i class="fa-solid fa-file-invoice text-primary mr-2"></i> পেমেন্ট সামারি</h3>
            
            <div class="space-y-2 font-bangla text-sm text-gray-600">
                <div class="flex justify-between items-center">
                    <span>অর্ডারের তারিখ:</span>
                    <span class="en-font font-bold"><?= date('d M Y, h:i A', strtotime($order['created_at'])) ?></span>
                </div>
                <!-- Delivery charge info (Assuming 70 or 120 based on calculation difference) -->
                <?php 
                    $subtotal = 0;
                    foreach($order_items as $itm) $subtotal += ($itm['unit_price'] * $itm['quantity']);
                    $delivery_charge = $order['total_amount'] - $subtotal;
                ?>
                <div class="flex justify-between items-center mt-2">
                    <span>প্রোডাক্ট প্রাইস:</span>
                    <span class="en-font font-bold">৳ <?= number_format($subtotal, 2) ?></span>
                </div>
                <div class="flex justify-between items-center">
                    <span>ডেলিভারি চার্জ:</span>
                    <span class="en-font font-bold">৳ <?= number_format($delivery_charge, 2) ?></span>
                </div>
                <div class="border-t pt-2 mt-2 flex justify-between items-center">
                    <span class="text-base font-bold text-gray-800">সর্বমোট (Total):</span>
                    <span class="text-xl font-bold text-primary en-font">৳ <?= number_format($order['total_amount'], 2) ?></span>
                </div>
            </div>
            
            <div class="mt-4 bg-yellow-50 text-yellow-700 border border-yellow-200 text-xs p-3 rounded text-center font-bangla font-bold">
                পেমেন্ট মেথড: ক্যাশ অন ডেলিভারি (COD)
            </div>
        </div>

    </div>
</div>

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