<?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() || $_SESSION['user_type'] !== 'seller') {
    redirect('../login.php');
}

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

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

// Fetch categories ONLY if Admin allowed them to show (show_to_seller = 1)
$categories = $db->select("SELECT * FROM service_categories WHERE status = 1 AND show_to_seller = 1 ORDER BY display_order ASC");

// Safely map Seller's Assigned Categories
$sidebar_allowed_cats = [];
// Default to 1 and 5 if the admin hasn't assigned categories to this seller yet
$seller_cat_ids = !empty($user['seller_categories']) ? explode(',', $user['seller_categories']) : [1, 5]; 

foreach($categories as $cat) {
    if(in_array($cat['id'], $seller_cat_ids)) {
        $sidebar_allowed_cats[] = $cat;
    }
}

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

// Handle Order Status Update & Commission Distribution
if(isset($_POST['update_status'])) {
    $order_id = intval($_POST['order_id']);
    $new_status = sanitize($_POST['status']);
    
    // Check old status to prevent duplicate commission
    $order_info = $db->select("SELECT * FROM orders WHERE id = ? AND seller_id = ?", [$order_id, $user_id]);
    
    if (!empty($order_info)) {
        $old_status = $order_info[0]['status'];
        $amount = floatval($order_info[0]['amount']);
        $service_name = $order_info[0]['service_name'];
        
        $db->insert("UPDATE orders SET status = ? WHERE id = ? AND seller_id = ?", [$new_status, $order_id, $user_id]);
        
        // Release any seller share that was held until completion
        if ($new_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 ($new_status === 'Completed' && $old_status !== 'Completed') {
            $admin_comm_pct = floatval(getSetting('admin_commission_pct', '10'));
            $admin_cut = ($amount * $admin_comm_pct) / 100;
            $seller_earn = $amount - $admin_cut;

            wallet_credit($db, $user_id, WALLET_MAIN, $seller_earn, [
                'category' => 'seller_share',
                'description' => "Sold: $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' . ($filter_cat > 0 ? "?cat_id=$filter_cat" : ""));
}

$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, '/');
$profile_image_url = !empty($user['profile_pic']) ? '../uploads/profiles/' . $user['profile_pic'] : null;

// Fetch Orders (Filtered if cat_id is present)
// We join with seller_services to determine which category the ordered service belongs to
if ($filter_cat > 0) {
    $orders = $db->select("
        SELECT o.*, u.name as buyer_name, u.mobile as buyer_mobile 
        FROM orders o 
        JOIN users u ON o.user_id = u.id 
        JOIN seller_services ss ON o.service_name = ss.title AND o.seller_id = ss.seller_id
        WHERE o.seller_id = ? AND ss.category_id = ? 
        ORDER BY o.created_at DESC
    ", [$user_id, $filter_cat]);
} else {
    $orders = $db->select("
        SELECT o.*, u.name as buyer_name, u.mobile as buyer_mobile 
        FROM orders o 
        JOIN users u ON o.user_id = u.id 
        WHERE o.seller_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>Customer Orders - WBMCZ Seller</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; } .font-poppins { font-family: 'Poppins', sans-serif; } .hide-scrollbar::-webkit-scrollbar { display: none; }</style>
</head>
<?php
/* ===== Premium shared layout (Navy + Gold) ===== */
require_once __DIR__ . '/../includes/theme.php';
$__scats = [];
if (isset($categories)) { $__ids = isset($seller_cat_ids) ? $seller_cat_ids : null; foreach ($categories as $__c) { if ($__ids === null || in_array($__c['id'], $__ids)) $__scats[] = $__c; } }
$__menu = theme_seller_menu($__scats);
theme_open([
    'panel'  => 'seller',
    'base'   => '../',
    'title'  => 'Customer Orders',
    '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-8">
                
                <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-4">
                    <div>
                        <h2 class="text-2xl font-bold text-gray-800 mb-1">
                            <?php 
                            if ($filter_cat > 0) {
                                $found = false;
                                foreach($sidebar_allowed_cats as $c) { 
                                    if($c['id'] == $filter_cat) { 
                                        echo htmlspecialchars($c['title']); 
                                        $found = true;
                                        break; 
                                    } 
                                }
                                if(!$found) echo "Filtered Orders";
                            } else {
                                echo "All Manage Orders";
                            }
                            ?>
                        </h2>
                        <p class="text-gray-500 text-sm">Update the status of the orders placed by customers. You get paid when an order is Completed.</p>
                    </div>
                </div>

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

                <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 ID & Date</th>
                                    <th class="p-4 font-semibold">Customer Info</th>
                                    <th class="p-4 font-semibold">Service</th>
                                    <th class="p-4 font-semibold">Amount</th>
                                    <th class="p-4 pr-6 font-semibold text-right">Status Action</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">#ORD-<?php echo 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">
                                        <p class="font-bold text-sm text-gray-800"><?php echo htmlspecialchars($ord['buyer_name']); ?></p>
                                        <p class="text-xs text-gray-500"><i class="fas fa-phone-alt text-[10px] mr-1"></i> <?php echo htmlspecialchars($ord['buyer_mobile']); ?></p>
                                    </td>
                                    <td class="p-4">
                                        <span class="font-semibold text-teal-700 text-sm"><?php echo htmlspecialchars($ord['service_name']); ?></span>
                                    </td>
                                    <td class="p-4">
                                        <span class="font-bold text-gray-800">₹<?php echo number_format($ord['amount'], 2); ?></span>
                                    </td>
                                    <td class="p-4 pr-6 text-right">
                                        <form method="POST" class="flex items-center justify-end space-x-2" onsubmit="return confirm('Are you sure you want to update this order status?');">
                                            <input type="hidden" name="order_id" value="<?php echo $ord['id']; ?>">
                                            <select name="status" class="px-2 py-1 border border-gray-300 rounded text-xs font-semibold focus:outline-none focus:border-teal-500 bg-white">
                                                <option value="Pending" <?php echo $ord['status']=='Pending'?'selected':''; ?>>Pending</option>
                                                <option value="Processing" <?php echo $ord['status']=='Processing'?'selected':''; ?>>Processing</option>
                                                <option value="Completed" <?php echo $ord['status']=='Completed'?'selected':''; ?>>Completed</option>
                                                <option value="Failed" <?php echo $ord['status']=='Failed'?'selected':''; ?>>Failed</option>
                                            </select>
                                            <button type="submit" name="update_status" class="bg-teal-600 text-white px-2 py-1.5 rounded text-xs hover:bg-teal-700 transition-colors shadow-sm">Update</button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="5" class="p-12 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-box-open"></i>
                                            </div>
                                            <p class="text-lg font-medium">No customer orders found in this category.</p>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

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