<?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/wallet.php';
require_once __DIR__ . '/../includes/shares.php';

if (!isLoggedIn() || !isAdmin()) { redirect('../login.php'); }
if (!hasPermission('manage_orders')) { die("Access Denied: You do not have permission to manage orders."); }

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

$can_users = hasPermission('manage_users');
$can_sellers = hasPermission('manage_sellers');
$can_staff = hasPermission('manage_staff_roles');
$can_services = hasPermission('manage_services');
$can_orders = hasPermission('manage_orders');
$can_transactions = hasPermission('manage_transactions');
$can_tickets = hasPermission('manage_tickets');
$can_settings = hasPermission('manage_settings');

// Handle Order Status Update and Admin Commission distribution
if (isset($_POST['update_order'])) {
    $order_id = intval($_POST['order_id']);
    $status = sanitize($_POST['status']);
    
    // Check old status to prevent duplicate commission triggering
    $order_info = $db->select("SELECT * FROM orders WHERE id = ?", [$order_id]);
    
    if (!empty($order_info)) {
        $old_status = $order_info[0]['status'];
        $seller_id = $order_info[0]['seller_id'];
        $service_name = $order_info[0]['service_name'];
        $amount = floatval($order_info[0]['amount']);
        
        $db->insert("UPDATE orders SET status = ? WHERE id = ?", [$status, $order_id]);
        
        // Release any seller share that was held until completion
        if ($status === 'Completed' && $old_status !== 'Completed') {
            shares_release_order($db, $order_id, 'Completed');
        }

        // --- ADMIN COMMISSION LOGIC ---
        // Only pay the seller when the order becomes Completed
        if ($status === 'Completed' && $old_status !== 'Completed' && $seller_id > 0) {
            $admin_comm_pct = floatval(getSetting('admin_commission_pct', '10'));
            $admin_cut = ($amount * $admin_comm_pct) / 100;
            $seller_earn = $amount - $admin_cut;

            wallet_credit($db, $seller_id, WALLET_MAIN, $seller_earn, [
                'category' => 'seller_share',
                'description' => "Earned: $service_name (Admin Fee: {$admin_comm_pct}%)",
                'reference_type' => 'order', 'reference_id' => $order_id ?? null,
            ]);
        }
        
        $_SESSION['flash_success'] = "Order status updated successfully!";
    }
    redirect('orders.php' . (!empty($_GET['cat_id']) ? '?cat_id=' . (int)$_GET['cat_id'] : ''));
}

if (isset($_POST['delete_order'])) {
    $del_id = intval($_POST['order_id']);
    $db->insert("DELETE FROM orders WHERE id = ?", [$del_id]);
    $_SESSION['flash_success'] = "Order deleted successfully!";
    redirect('orders.php' . (!empty($_GET['cat_id']) ? '?cat_id=' . (int)$_GET['cat_id'] : ''));
}

/* ===========================================================================
   CATEGORY-WISE ORDER MANAGEMENT
   ---------------------------------------------------------------------------
   The sidebar links this page as orders.php?cat_id=N for each of the service
   categories. `orders.category_id` is added by ccpsimigration.php; the block
   below also self-heals if the migration has not been run yet.
   ======================================================================== */
$__conn = $db->getConnection();
try {
    $r = $__conn->query("SHOW COLUMNS FROM orders LIKE 'category_id'");
    if ($r && $r->num_rows === 0) {
        $__conn->query("ALTER TABLE orders ADD COLUMN `category_id` INT NULL DEFAULT NULL AFTER `service_name`");
        $__conn->query("ALTER TABLE orders ADD INDEX idx_orders_cat (category_id)");
    }
} catch (\Throwable $e) { /* ignore — the filter simply shows everything */ }

$filter_cat = isset($_GET['cat_id']) ? (int)$_GET['cat_id'] : 0;

$categories = [];
try {
    $categories = $db->select("SELECT id, title, icon_class FROM service_categories WHERE COALESCE(status,1)=1 ORDER BY display_order ASC, id ASC");
} catch (\Throwable $e) { $categories = []; }

/* Per-category counters for the filter chips */
$cat_counts = [];
$total_orders_all = 0;
try {
    foreach ($db->select("SELECT COALESCE(category_id,0) c, COUNT(*) n FROM orders GROUP BY COALESCE(category_id,0)") as $row) {
        $cat_counts[(int)$row['c']] = (int)$row['n'];
        $total_orders_all += (int)$row['n'];
    }
} catch (\Throwable $e) {}

$order_where  = '1';
$order_params = [];
if ($filter_cat > 0) {
    $order_where    = 'o.category_id = ?';
    $order_params[] = $filter_cat;
}

$orders = $db->select(
    "SELECT o.*, u.name as customer_name, u.mobile as customer_mobile, s.name as seller_name
       FROM orders o
       JOIN users u ON o.user_id = u.id
       LEFT JOIN users s ON o.seller_id = s.id
      WHERE $order_where
      ORDER BY o.created_at DESC",
    $order_params
);

$active_cat_title = 'All Orders';
foreach ($categories as $c) {
    if ((int)$c['id'] === $filter_cat) { $active_cat_title = html_entity_decode($c['title'], ENT_QUOTES, 'UTF-8'); break; }
}

$company_logo = getSetting('company_logo', '../assets/images/logo.png');
$company_name = getSetting('company_name', 'WBMCZ');
?>
<!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>Manage Orders - Admin Panel</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=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style> body { font-family: 'Inter', sans-serif; } .hide-scrollbar::-webkit-scrollbar { display: none; } </style>
</head>
<body class="bg-gray-50" x-data="{ sidebarOpen: window.innerWidth >= 768, orderModal: false, activeOrder: {} }">

    <div class="flex h-screen overflow-hidden">
        
        <?php include __DIR__ . '/includes/sidebar.php'; ?>
        <div class="flex-1 flex flex-col min-w-0 bg-gray-100 overflow-hidden">
            <header class="h-20 bg-white text-slate-800 flex items-center justify-between px-4 shadow-sm border-b border-gray-200 z-40 relative">
                <div class="flex items-center"><button @click="sidebarOpen = !sidebarOpen" class="p-2 mr-3 text-slate-500 hover:text-emerald-600 rounded-lg"><i class="fas fa-bars text-xl"></i></button><h2 class="text-xl font-bold hidden md:block text-slate-800">Manage Orders</h2></div>
            </header>

            <main class="flex-1 overflow-y-auto p-4 md:p-6">
                
                <?php if (isset($_SESSION['flash_success'])): ?>
                <div class="mb-6 bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-xl flex items-center shadow-sm">
                    <i class="fas fa-check-circle mr-2"></i><span class="font-medium"><?php echo $_SESSION['flash_success']; unset($_SESSION['flash_success']); ?></span>
                </div>
                <?php endif; ?>

                <!-- ============ CATEGORY FILTER ============ -->
                <div class="mb-6">
                    <div class="flex items-baseline justify-between gap-3 mb-3 flex-wrap">
                        <h3 class="text-lg font-extrabold text-slate-800"><?php echo htmlspecialchars($active_cat_title); ?></h3>
                        <p class="text-xs text-slate-400 font-semibold"><?php echo number_format(count($orders)); ?> order<?php echo count($orders) === 1 ? '' : 's'; ?> shown</p>
                    </div>
                    <div class="flex flex-wrap gap-2">
                        <?php
                        $chip_on  = 'bg-slate-900 text-white ring-slate-900 shadow-lg shadow-slate-900/20';
                        $chip_off = 'bg-white text-slate-600 ring-slate-200 hover:bg-slate-50 hover:text-slate-900';
                        ?>
                        <a href="orders.php" class="inline-flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-bold ring-1 transition-all <?php echo $filter_cat === 0 ? $chip_on : $chip_off; ?>">
                            <i class="fas fa-layer-group text-[.7rem]"></i> All Orders
                            <?php if ($total_orders_all > 0): ?><span class="opacity-60"><?php echo $total_orders_all; ?></span><?php endif; ?>
                        </a>
                        <?php foreach ($categories as $c):
                            $cid = (int)$c['id'];
                            $n   = $cat_counts[$cid] ?? 0; ?>
                            <a href="orders.php?cat_id=<?php echo $cid; ?>"
                               class="inline-flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-bold ring-1 transition-all <?php echo $filter_cat === $cid ? $chip_on : $chip_off; ?>">
                                <i class="fas <?php echo htmlspecialchars($c['icon_class'] ?: 'fa-circle-dot'); ?> text-[.7rem]"></i>
                                <?php echo htmlspecialchars(html_entity_decode($c['title'], ENT_QUOTES, 'UTF-8')); ?>
                                <?php if ($n > 0): ?><span class="opacity-60"><?php echo $n; ?></span><?php endif; ?>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                    <div class="overflow-x-auto">
                        <table class="w-full text-left border-collapse">
                            <thead>
                                <tr class="bg-gray-50 text-xs text-gray-500 uppercase tracking-wider border-b border-gray-100">
                                    <th class="p-4 pl-6 font-semibold">Order Info</th>
                                    <th class="p-4 font-semibold">Service & Seller</th>
                                    <th class="p-4 font-semibold text-right">Amount</th>
                                    <th class="p-4 font-semibold text-center">Status</th>
                                    <th class="p-4 pr-6 font-semibold text-right">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-50">
                                <?php if(!empty($orders)): foreach($orders as $order): ?>
                                <tr class="hover:bg-gray-50 transition-colors">
                                    <td class="p-4 pl-6">
                                        <p class="font-bold text-gray-800 text-sm"><?php echo htmlspecialchars($order['customer_name']); ?></p>
                                        <p class="text-xs text-gray-500"><i class="fas fa-phone-alt text-[10px] mr-1"></i><?php echo htmlspecialchars($order['customer_mobile']); ?></p>
                                        <p class="text-[10px] text-gray-400 mt-1"><?php echo date('d M Y, h:i A', strtotime($order['created_at'])); ?></p>
                                    </td>
                                    <td class="p-4">
                                        <p class="font-bold text-slate-700 text-sm"><?php echo htmlspecialchars($order['service_name']); ?></p>
                                        <?php if($order['seller_id'] > 0): ?>
                                            <p class="text-xs text-emerald-600 font-semibold"><i class="fas fa-store mr-1"></i> <?php echo htmlspecialchars($order['seller_name']); ?></p>
                                        <?php else: ?>
                                            <p class="text-xs text-blue-600 font-semibold"><i class="fas fa-server mr-1"></i> System Service</p>
                                        <?php endif; ?>
                                    </td>
                                    <td class="p-4 text-right font-extrabold text-gray-800">
                                        ₹<?php echo number_format($order['amount'], 2); ?>
                                    </td>
                                    <td class="p-4 text-center">
                                        <?php 
                                            $statusClass = 'bg-gray-100 text-slate-700';
                                            if($order['status'] == 'Completed') $statusClass = 'bg-emerald-100 text-emerald-700';
                                            elseif($order['status'] == 'Pending' || $order['status'] == 'Processing') $statusClass = 'bg-yellow-100 text-yellow-700';
                                            elseif($order['status'] == 'Failed' || $order['status'] == 'Cancelled') $statusClass = 'bg-rose-100 text-rose-700';
                                        ?>
                                        <span class="px-3 py-1 text-[10px] font-bold uppercase tracking-wider rounded-full <?php echo $statusClass; ?>">
                                            <?php echo htmlspecialchars($order['status']); ?>
                                        </span>
                                    </td>
                                    <td class="p-4 pr-6 text-right whitespace-nowrap">
                                        <button @click="activeOrder = { id: <?php echo $order['id']; ?>, customer: '<?php echo addslashes($order['customer_name']); ?>', service: '<?php echo addslashes($order['service_name']); ?>', status: '<?php echo $order['status']; ?>' }; orderModal = true;" class="w-8 h-8 rounded-lg bg-blue-50 hover:bg-blue-100 text-blue-600 transition-colors inline-flex items-center justify-center tooltip mr-1">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <form method="POST" class="inline-block" onsubmit="return confirm('Delete this order?');">
                                            <input type="hidden" name="order_id" value="<?php echo $order['id']; ?>">
                                            <button type="submit" name="delete_order" class="w-8 h-8 rounded-lg bg-rose-50 hover:bg-rose-100 text-rose-600 transition-colors inline-flex items-center justify-center tooltip">
                                                <i class="fas fa-trash-alt"></i>
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; else: ?>
                                    <tr><td colspan="5" class="p-8 text-center text-gray-500">No orders found.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

            </main>
        </div>
    </div>

    <div x-show="orderModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4" style="display:none;">
        <div @click.away="orderModal = false" x-transition.scale.origin.top class="bg-white rounded-2xl shadow-2xl w-full max-w-sm overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-100 flex justify-between items-center bg-gray-50">
                <h3 class="font-bold text-gray-900 text-lg">Update Order Status</h3>
                <button @click="orderModal = false" class="text-gray-400 hover:text-rose-500"><i class="fas fa-times text-xl"></i></button>
            </div>
            <div class="p-6">
                <div class="bg-slate-50 p-4 rounded-xl mb-6 border border-slate-100">
                    <p class="text-xs text-gray-500">Customer</p>
                    <p class="font-bold text-slate-800 mb-2" x-text="activeOrder.customer"></p>
                    <p class="text-xs text-gray-500">Service Name</p>
                    <p class="font-bold text-lg text-slate-800" x-text="activeOrder.service"></p>
                </div>
                
                <form method="POST">
                    <input type="hidden" name="order_id" x-model="activeOrder.id">
                    <div class="mb-6">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Order Status</label>
                        <select name="status" x-model="activeOrder.status" class="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-emerald-500 font-semibold text-slate-700">
                            <option value="Pending">Pending</option>
                            <option value="Processing">Processing</option>
                            <option value="Completed">Completed</option>
                            <option value="Failed">Failed</option>
                            <option value="Cancelled">Cancelled</option>
                        </select>
                    </div>
                    <button type="submit" name="update_order" class="w-full bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-3 px-6 rounded-xl shadow-md transition-colors flex items-center justify-center">
                        <i class="fas fa-check-circle mr-2"></i> Save Status
                    </button>
                </form>
            </div>
        </div>
    </div>
</body>
</html>
