<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/Language.php';
require_once __DIR__ . '/includes/shares.php';
require_once __DIR__ . '/includes/wallet.php';
require_once __DIR__ . '/includes/purchase.php';

// Ensure user is logged in
if (!isLoggedIn()) {
    redirect('login.php');
}

$lang = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id = $_SESSION['user_id'];

/* The visit / advance columns are added on demand, so an order list never
   white-screens on a server where ordmigration.php has not been run yet. */
buy_ensure_schema($db);

// Fetch user data
$user_data = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
$user = !empty($user_data) ? $user_data[0] : null;

$unread_notifs = $db->select("SELECT * FROM notifications WHERE user_id = ? AND is_read = 0 ORDER BY created_at DESC LIMIT 5", [$user_id]);
$unread_count = count($unread_notifs);

$wallet_balance = isset($user['wallet_balance']) ? $user['wallet_balance'] : '0.00';
$company_logo = getSetting('company_logo', 'assets/images/logo.png');
$company_logo = (strpos($company_logo, 'http') === 0) ? $company_logo : ltrim($company_logo, '/');
$company_name = getSetting('company_name', 'WBMCZ');
$profile_image_url = !empty($user['profile_pic']) ? 'uploads/profiles/' . $user['profile_pic'] : null;

// Determine dashboard link based on role
$dashboard_link = 'dashboard.php';
if ($user['user_type'] == 'seller') { $dashboard_link = 'seller/index.php'; } 
elseif ($user['user_type'] == 'admin') { $dashboard_link = 'admin/index.php'; }

// Fetch ALL active categories for the Sidebar Dropdown
$all_categories = $db->select("SELECT * FROM service_categories WHERE status = 1 ORDER BY display_order ASC");
$sidebar_subcats = [1 => [], 5 => []];
foreach ($db->select("SELECT id, category_id, title, icon_class FROM agency_sub_categories WHERE category_id IN (1,5) AND status = 1 ORDER BY category_id, id") as $__r) { $sidebar_subcats[$__r['category_id']][] = $__r; }

// Check if filtering by a specific category
$filter_cat = isset($_GET['cat_id']) ? intval($_GET['cat_id']) : 0;

// Fetch User's Orders with Seller Contact Info & Filter by Category
if ($filter_cat > 0) {
    $orders = $db->select("
        SELECT o.*, u.name as seller_name, u.call_number, u.whatsapp_number 
        FROM orders o 
        LEFT JOIN users u ON o.seller_id = u.id 
        JOIN seller_services ss ON o.service_name = ss.title AND o.seller_id = ss.seller_id
        WHERE o.user_id = ? AND ss.category_id = ? 
        ORDER BY o.created_at DESC
    ", [$user_id, $filter_cat]);
} else {
    $orders = $db->select("
        SELECT o.*, u.name as seller_name, u.call_number, u.whatsapp_number 
        FROM orders o 
        LEFT JOIN users u ON o.seller_id = u.id 
        WHERE o.user_id = ? 
        ORDER BY o.created_at DESC
    ", [$user_id]);
}
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Order History - <?php echo htmlspecialchars($company_name); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style> body { font-family: 'Inter', sans-serif; scroll-behavior: smooth; } .font-poppins { font-family: 'Poppins', sans-serif; } .hide-scrollbar::-webkit-scrollbar { display: none; } .hide-scrollbar { -ms-overflow-style: none; scrollbar-width: none; } </style>
</head>
<?php
/* ===== Premium shared layout (Navy + Gold) ===== */
require_once __DIR__ . '/includes/theme.php';
$__cats = isset($all_categories) ? $all_categories : $db->select("SELECT * FROM service_categories WHERE status = 1 ORDER BY display_order ASC");
$__subs = isset($sidebar_subcats) ? $sidebar_subcats : null;
if ($__subs === null) { $__subs = [1=>[],5=>[]]; foreach ($db->select("SELECT id, category_id, title, icon_class FROM agency_sub_categories WHERE category_id IN (1,5) AND status = 1 ORDER BY category_id, id") as $__r) { $__subs[$__r['category_id']][] = $__r; } }
$__menu = theme_user_menu($__subs, $__cats);
theme_open([
    'panel'  => 'user',
    'base'   => '',
    'title'  => 'Order History',
    'active' => 'orders',
    'user'   => isset($user) ? $user : ['name' => 'User', 'mobile' => ''],
    'wallet' => isset($wallet_balance) ? $wallet_balance : 0,
    'notifs' => isset($unread_notifs) ? $unread_notifs : [],
    'logo'   => isset($company_logo) ? $company_logo : 'assets/images/logo.png',
    'brand'  => isset($company_name) ? $company_name : 'WBMCZ',
    'menu'   => $__menu,
    'state'  => '',
]);
?>

            <main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8 relative">

                <div class="mb-6">
                    <h2 class="text-2xl font-bold text-gray-800 mb-1">
                        <?php 
                        if ($filter_cat > 0) {
                            $found = false;
                            foreach($all_categories as $c) { 
                                if($c['id'] == $filter_cat) { 
                                    echo htmlspecialchars($c['title']) . " Orders"; 
                                    $found = true;
                                    break; 
                                } 
                            }
                            if(!$found) echo "Filtered Orders";
                        } else {
                            echo "All Your Orders";
                        }
                        ?>
                    </h2>
                    <p class="text-gray-500 text-sm">View and track all your past purchases and service requests.</p>
                </div>

                <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden mb-20">
                    <div class="overflow-x-auto">
                        <table class="w-full text-left border-collapse">
                            <thead>
                                <tr class="bg-indigo-50/50 text-xs text-gray-500 uppercase tracking-wider border-b border-indigo-100">
                                    <th class="p-4 pl-6 font-semibold border-b border-gray-200">Order ID & Date</th>
                                    <th class="p-4 font-semibold border-b border-gray-200">Service Details</th>
                                    <th class="p-4 font-semibold border-b border-gray-200">Seller Contact</th>
                                    <th class="p-4 font-semibold border-b border-gray-200">Payment</th>
                                    <th class="p-4 font-semibold border-b border-gray-200 text-right">Status</th>
                                    <th class="p-4 pr-6 font-semibold border-b border-gray-200 text-right">Track</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-50">
                                <?php if(!empty($orders)): foreach($orders as $ord): ?>
                                <tr class="hover:bg-gray-50 transition-colors">
                                    <td class="p-4 pl-6">
                                        <p class="font-bold text-gray-800"><?php echo htmlspecialchars(!empty($ord['order_code']) ? $ord['order_code'] : ('#ORD-' . str_pad($ord['id'], 5, '0', STR_PAD_LEFT))); ?></p>
                                        <p class="text-xs text-gray-500 mt-1"><?php echo date('d M Y, h:i A', strtotime($ord['created_at'])); ?></p>
                                    </td>
                                    <td class="p-4">
                                        <span class="font-bold text-indigo-700 text-sm"><?php echo htmlspecialchars($ord['service_name']); ?></span>
                                        <?php if (($ord['fulfilment'] ?? 'online') === 'visit'): ?>
                                            <span class="ml-1 px-2 py-0.5 rounded-full bg-amber-50 text-amber-700 border border-amber-200 text-[10px] font-bold whitespace-nowrap">
                                                <i class="fas fa-person-walking"></i> Visit
                                            </span>
                                        <?php endif; ?>
                                        <?php if ((int)($ord['item_count'] ?? 1) > 1): ?>
                                            <p class="text-[11px] text-gray-400 mt-0.5"><?php echo (int)$ord['item_count']; ?> items in this order</p>
                                        <?php endif; ?>
                                    </td>
                                    <td class="p-4">
                                        <?php if (!empty($ord['seller_name'])): ?>
                                            <p class="font-bold text-xs text-gray-700 mb-1"><i class="fas fa-store text-gray-400 mr-1"></i> <?php echo htmlspecialchars($ord['seller_name']); ?></p>
                                            
                                            <?php if(in_array($ord['status'], ['Pending', 'Processing'])): ?>
                                                <div class="flex space-x-2 mt-2">
                                                    <?php if(!empty($ord['call_number'])): ?>
                                                        <a href="tel:<?php echo htmlspecialchars($ord['call_number']); ?>" class="w-7 h-7 bg-indigo-100 text-indigo-600 rounded-full flex items-center justify-center hover:bg-indigo-200 transition-colors tooltip" title="Call Seller"><i class="fas fa-phone-alt text-[10px]"></i></a>
                                                    <?php endif; ?>
                                                    <?php if(!empty($ord['whatsapp_number'])): ?>
                                                        <a href="https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $ord['whatsapp_number']); ?>" target="_blank" class="w-7 h-7 bg-green-100 text-green-600 rounded-full flex items-center justify-center hover:bg-green-200 transition-colors tooltip" title="WhatsApp Seller"><i class="fab fa-whatsapp text-[12px]"></i></a>
                                                    <?php endif; ?>
                                                </div>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <span class="text-xs text-gray-400 italic">System Service</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="p-4">
                                        <span class="font-extrabold text-gray-800">₹<?php echo number_format($ord['amount'], 2); ?></span>
                                        <?php $__due = (float)($ord['due_amount'] ?? 0); if ($__due > 0): ?>
                                            <p class="text-[11px] font-bold text-amber-700 mt-0.5">₹<?php echo number_format($__due, 2); ?> still to pay</p>
                                        <?php elseif ((float)($ord['paid_amount'] ?? 0) > 0): ?>
                                            <p class="text-[11px] font-bold text-emerald-600 mt-0.5">Fully paid</p>
                                        <?php endif; ?>
                                        <?php if (!empty($ord['payment_code']) && ($ord['payment_code_status'] ?? '') === 'pending'): ?>
                                            <p class="text-[11px] font-bold text-indigo-600 mt-0.5">Code <?php echo htmlspecialchars($ord['payment_code']); ?></p>
                                        <?php endif; ?>
                                    </td>
                                    <td class="p-4 text-right">
                                        <?php 
                                        $status_class = 'bg-gray-100 text-gray-700';
                                        $icon = 'fa-circle-info';
                                        
                                        if($ord['status'] == 'Completed') {
                                            $status_class = 'bg-emerald-100 text-emerald-700 border border-emerald-200';
                                            $icon = 'fa-check-circle';
                                        } elseif($ord['status'] == 'Pending' || $ord['status'] == 'Processing') {
                                            $status_class = 'bg-yellow-100 text-yellow-700 border border-yellow-200';
                                            $icon = 'fa-clock';
                                        } elseif($ord['status'] == 'Failed') {
                                            $status_class = 'bg-rose-100 text-rose-700 border border-rose-200';
                                            $icon = 'fa-times-circle';
                                        }
                                        ?>
                                        <?php
                                        /* The stage says more than the status once visits are involved. */
                                        $__stage = (string)($ord['stage'] ?? '');
                                        $__label = $ord['status'];
                                        if ($__stage !== '' && $__stage !== 'completed' && $ord['status'] !== 'Cancelled') {
                                            $__m = buy_stage_meta($__stage);
                                            $__label = $__m[0];
                                            $icon    = $__m[1];
                                        }
                                        ?>
                                        <span class="px-2.5 py-1 text-[10px] font-bold uppercase tracking-wider rounded-md <?php echo $status_class; ?> inline-flex items-center">
                                            <i class="fas <?php echo $icon; ?> mr-1"></i> <?php echo htmlspecialchars($__label); ?>
                                        </span>
                                    </td>
                                    <td class="p-4 pr-6 text-right">
                                        <a href="order.php?id=<?php echo (int)$ord['id']; ?>"
                                           class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-slate-900 text-white text-[11px] font-bold hover:bg-slate-700 whitespace-nowrap">
                                            <i class="fas fa-route"></i> Track
                                        </a>
                                    </td>
                                </tr>
                                <?php endforeach; else: ?>
                                    <tr>
                                        <td colspan="6" class="p-16 text-center text-gray-500">
                                            <div class="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center mx-auto mb-4 text-gray-300 text-2xl border border-gray-100">
                                                <i class="fas fa-shopping-basket"></i>
                                            </div>
                                            <p class="text-lg font-medium">You haven't placed any orders yet.</p>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

            </main>
        </div>
    </div>
</body>
</html>