<?php
session_start();
include 'db_config.php';

// Sync persistence via cookie for customers
if (!isset($_SESSION['customer_id']) && isset($_COOKIE['customer_login'])) {
    $phone = $_COOKIE['customer_login'];
    $stmt = $conn->prepare("SELECT id FROM customers WHERE phone = ?");
    $stmt->bind_param("s", $phone);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res->num_rows > 0) {
        $customer = $res->fetch_assoc();
        $_SESSION['customer_id'] = $customer['id'];
        $_SESSION['customer_phone'] = $phone;
        $_SESSION['role'] = 'customer';
    }
    $stmt->close();
}

// Check access
if(!isset($_SESSION['role'])) {
    header("Location: customer_login.php");
    exit();
}

include 'functions.php';
include_once 'categories.php';
include_once 'districts.php';

$cat = isset($_GET['category']) ? sanitize_input($_GET['category']) : '';
$loc = isset($_GET['district']) ? sanitize_input($_GET['district']) : ''; 
$div = isset($_GET['division']) ? sanitize_input($_GET['division']) : ''; 

$query = "SELECT ed.* FROM employee_details ed WHERE status = 'Approved'";
if($cat) $query .= " AND job_category = '$cat'";
if($loc) $query .= " AND district = '$loc'"; 
if($div) $query .= " AND divisional_secretariat = '$div'"; 

$results = $conn->query($query);

// Get counts for each category
$counts_query = "SELECT job_category, COUNT(*) as count FROM employee_details WHERE status = 'Approved' GROUP BY job_category";
$counts_res = $conn->query($counts_query);
$cat_counts = [];
if($counts_res) {
    while($row = $counts_res->fetch_assoc()) {
        $cat_counts[$row['job_category']] = $row['count'];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Find Workers | Work For Sri Lanka</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/lucide@latest"></script>
    <style>
        body { font-family: 'Inter', sans-serif; }
        @keyframes pop {
            0% { transform: scale(0.95); opacity: 0; }
            70% { transform: scale(1.05); opacity: 1; }
            100% { transform: scale(1); opacity: 1; }
        }
        .brand-pop {
            transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
            display: inline-block;
        }
        .brand-pop:hover {
            transform: scale(1.15);
        }
        .custom-scrollbar::-webkit-scrollbar {
            width: 4px;
        }
        .custom-scrollbar::-webkit-scrollbar-track {
            background: rgba(15, 23, 42, 1);
        }
        .custom-scrollbar::-webkit-scrollbar-thumb {
            background: rgba(79, 70, 229, 0.3);
            border-radius: 10px;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover {
            background: rgba(79, 70, 229, 0.5);
        }
    </style>
    <?php
    function get_category_icon_name($category) {
        $c = strtolower($category);
        if (strpos($c, 'mason') !== false) return 'hammer';
        if (strpos($c, 'carpenter') !== false) return 'drill';
        if (strpos($c, 'tile') !== false) return 'layout-grid';
        if (strpos($c, 'plumber') !== false) return 'droplets';
        if (strpos($c, 'electric') !== false) return 'zap';
        if (strpos($c, 'paint') !== false) return 'paint-brush';
        if (strpos($c, 'landscap') !== false) return 'sprout';
        if (strpos($c, 'stone') !== false || strpos($c, 'sand') !== false || strpos($c, 'soil') !== false) return 'truck';
        if (strpos($c, 'repair') !== false || strpos($c, 'equip') !== false) return 'settings';
        if (strpos($c, 'contract') !== false) return 'hard-hat';
        if (strpos($c, 'weld') !== false) return 'flame';
        if (strpos($c, 'aluminiu') !== false) return 'frame';
        if (strpos($c, 'cctv') !== false) return 'camera';
        if (strpos($c, 'ceil') !== false) return 'layers';
        if (strpos($c, 'clean') !== false) return 'sparkles';
        if (strpos($c, 'curtain') !== false) return 'wind';
        if (strpos($c, 'mover') !== false) return 'package';
        if (strpos($c, 'pest') !== false) return 'bug';
        if (strpos($c, 'vehicle') !== false) return 'car';
        if (strpos($c, 'well') !== false) return 'waves';
        if (strpos($c, 'other') !== false) return 'more-horizontal';
        return 'briefcase';
    }
    ?>
</head>
<body class="bg-slate-950 min-h-screen flex flex-col text-slate-200 selection:bg-indigo-500 selection:text-white">
    
    <!-- Navbar -->
    <nav class="bg-slate-900 border-b border-slate-800 sticky top-0 z-50">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-20 items-center">
                <div class="flex-shrink-0 flex items-center gap-3">
                    <a href="<?= BASE_URL ?>/index.php" class="brand-pop block">
                        <img src="assets/images/logo_banner.png" alt="Department of Manpower and Employment" class="h-10 md:h-12 object-contain">
                    </a>
                    <div class="h-8 w-px bg-slate-700 mx-2 hidden md:block"></div>
                    <a href="<?= BASE_URL ?>/index.php" class="text-xl md:text-2xl font-bold italic tracking-tighter text-white brand-pop block origin-left">
                        Work For <span class="text-indigo-400">Sri Lanka</span>
                    </a>
                </div>
                <div class="hidden md:flex space-x-8">
                    <a href="<?= BASE_URL ?>/index.php" class="text-slate-400 hover:text-indigo-400 font-medium transition">Home</a>
                    <a href="employee/register.php" class="text-slate-400 hover:text-indigo-400 font-medium transition">Join as Worker</a>
                    <a href="employer/register.php" class="text-slate-400 hover:text-indigo-400 font-medium transition">Post a Job</a>
                </div>
            </div>
        </div>
    </nav>

    <!-- Header & Search Section -->
    <div class="relative pt-10 pb-10 text-center overflow-hidden">
        <!-- Background Glow -->
        <div class="absolute top-0 left-1/2 -translate-x-1/2 w-full h-full bg-[radial-gradient(circle_at_center,_var(--tw-gradient-stops))] from-indigo-900/40 via-slate-900 to-slate-950 -z-10"></div>
        <div class="absolute inset-0 bg-[url('https://www.transparenttextures.com/patterns/cubes.png')] opacity-5 -z-10"></div>

        <div class="relative z-10 max-w-4xl mx-auto px-4">
            <h1 class="text-3xl md:text-5xl font-bold mb-4 text-white">Find the Best Workers in Sri Lanka</h1>
            <p class="text-slate-400 text-lg mb-8">Search for skilled professionals near you.</p>

            <!-- Search Card -->
            <div class="bg-slate-900/80 backdrop-blur-xl border border-slate-700 p-4 rounded-3xl shadow-2xl max-w-3xl mx-auto transform translate-y-4">
                <form method="get" class="flex flex-col md:flex-row gap-4">
                    <!-- Maintain Category in URL if active -->
                    <input type="hidden" name="category" value="<?= htmlspecialchars($cat) ?>">
                    
                    <div class="flex-1 text-left group">
                        <label class="block text-xs font-bold text-slate-400 uppercase tracking-wide mb-1 ml-1">Preferred District</label>
                        <select name="district" id="district-select" onchange="updateDivisions()" class="w-full bg-slate-800 border border-slate-700 text-white text-sm rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-transparent block p-3 transition h-[50px] outline-none">
                            <option value="" class="bg-slate-900">All Districts</option>
                            <?php
                            include_once 'districts.php';
                            $all_districts = get_districts();
                            foreach(array_keys($all_districts) as $d) {
                                $sel = ($loc == $d) ? 'selected' : '';
                                echo "<option value=\"$d\" $sel class='bg-slate-900'>$d</option>";
                            }
                            ?>
                        </select>
                    </div>

                    <div class="flex-1 text-left group">
                        <label class="block text-xs font-bold text-slate-400 uppercase tracking-wide mb-1 ml-1">Divisional Secretariat</label>
                        <select name="division" id="division-select" class="w-full bg-slate-800 border border-slate-700 text-white text-sm rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-transparent block p-3 transition h-[50px] outline-none">
                            <option value="" class="bg-slate-900">All Divisions</option>
                        </select>
                    </div>

                    <div class="flex items-end pb-[1px]">
                        <button type="submit" class="w-full md:w-auto h-[50px] px-8 bg-indigo-600 hover:bg-indigo-500 text-white font-bold rounded-xl shadow-lg shadow-indigo-600/20 hover:shadow-indigo-600/40 transition transform active:scale-[0.98] flex items-center justify-center gap-2">
                            <i data-lucide="search" class="w-5 h-5"></i>
                            Search
                        </button>
                    </div>
                    <?php if($cat || $loc || $div): ?>
                    <div class="flex items-end pb-[1px]">
                        <a href="search.php" class="w-full md:w-auto h-[50px] px-6 bg-slate-800 hover:bg-slate-700 text-slate-300 font-bold rounded-xl transition flex items-center justify-center">
                            <i data-lucide="refresh-cw" class="w-4 h-4"></i>
                        </a>
                    </div>
                    <?php endif; ?>
                </form>
            </div>
        </div>
    </div>

    <!-- Main Section -->
    <div class="container mx-auto px-4 pt-2 pb-12 flex-grow max-w-7xl">
        <div class="flex flex-col lg:flex-row gap-10">
            
            <!-- Sidebar - Categories -->
            <aside class="w-full lg:w-80 shrink-0">
                <div class="sticky top-20 bg-slate-900 border border-slate-800 rounded-[2.5rem] overflow-hidden shadow-2xl">
                    <div class="bg-indigo-600/10 px-8 py-5 border-b border-indigo-500/10">
                        <h3 class="text-[10px] font-black text-indigo-400 uppercase tracking-[0.2em] flex items-center gap-2">
                            <i data-lucide="grid" class="w-4 h-4"></i>
                            All Categories
                        </h3>
                    </div>
                    <div class="p-3">
                        <div class="space-y-1 max-h-[calc(100vh-300px)] overflow-y-auto custom-scrollbar pr-1">
                            <?php
                            $available_cats = get_job_categories();
                            foreach($available_cats as $category):
                                $isActive = ($cat == $category);
                                $icon = get_category_icon_name($category);
                                $count = isset($cat_counts[$category]) ? $cat_counts[$category] : 0;
                            ?>
                            <a href="search.php?category=<?=urlencode($category)?>&district=<?=$loc?>&division=<?=$div?>" 
                               class="flex items-center gap-4 px-4 py-3.5 rounded-2xl transition-all duration-300 group <?= $isActive ? 'bg-indigo-600 shadow-lg shadow-indigo-600/40 text-white' : 'hover:bg-slate-800 text-slate-400 hover:text-white' ?>">
                                <div class="w-12 h-12 shrink-0 flex items-center justify-center rounded-2xl <?= $isActive ? 'bg-white/20' : 'bg-slate-800 group-hover:bg-indigo-500/20 group-hover:text-indigo-400' ?> transition-all duration-300 shadow-inner">
                                    <i data-lucide="<?= $icon ?>" class="w-6 h-6"></i>
                                </div>
                                <div class="flex-grow flex flex-col min-w-0">
                                    <span class="text-sm font-bold truncate tracking-tight"><?= $category ?></span>
                                    <span class="text-[9px] font-black uppercase tracking-widest opacity-60"><?= $count ?> Professional<?= $count != 1 ? 's' : '' ?></span>
                                </div>
                                <?php if($isActive): ?>
                                    <i data-lucide="chevron-right" class="w-4 h-4 ml-auto opacity-50"></i>
                                <?php else: ?>
                                    <i data-lucide="arrow-right" class="w-4 h-4 ml-auto opacity-0 -translate-x-2 group-hover:opacity-10 group-hover:translate-x-0 transition-all"></i>
                                <?php endif; ?>
                            </a>
                            <?php endforeach; ?>
                        </div>
                        
                        <?php if($cat): ?>
                        <div class="mt-4 pt-4 border-t border-slate-800/50">
                             <a href="search.php?district=<?=$loc?>&division=<?=$div?>" class="flex items-center justify-center gap-2 px-4 py-3 rounded-2xl bg-slate-800/50 text-[10px] font-black text-slate-400 hover:text-white hover:bg-red-500/20 hover:border-red-500/20 transition-all uppercase tracking-widest border border-transparent">
                                 <i data-lucide="x" class="w-3 h-3"></i>
                                 Clear Category
                             </a>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </aside>

            <!-- Results Section -->
            <main class="flex-grow">
                <div class="flex flex-col md:flex-row justify-between items-end md:items-center mb-10 gap-4">
                    <div>
                        <h2 class="text-3xl font-black text-white tracking-tight flex items-center gap-3">
                            Available Professionals
                            <?php if($results->num_rows > 0): ?>
                                <span class="text-xs font-bold text-indigo-400 bg-indigo-500/10 border border-indigo-500/20 px-3 py-1 rounded-full uppercase tracking-widest"><?=$results->num_rows?> Found</span>
                            <?php endif; ?>
                        </h2>
                        <p class="text-slate-500 text-sm mt-1">Showing skilled workers available for hire.</p>
                    </div>
                    <?php if($cat || $loc): ?>
                         <a href="search.php" class="inline-flex items-center gap-2 text-xs font-black uppercase tracking-widest text-slate-500 hover:text-red-400 transition bg-slate-900 px-5 py-2.5 rounded-2xl border border-slate-800 hover:border-red-500/20 shadow-xl">
                            <i data-lucide="refresh-cw" class="w-4 h-4"></i>
                            Clear Filters
                        </a>
                    <?php endif; ?>
                </div>

                <?php if($results->num_rows > 0): ?>
                    <div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-8">
                        <?php while($w = $results->fetch_assoc()): ?>
                            <div class="bg-slate-900 rounded-[2rem] shadow-2xl border border-slate-800 overflow-hidden hover:border-indigo-500/50 transition-all duration-500 group hover:-translate-y-2">
                                
                                <!-- Header / Cover -->
                                <div class="h-28 bg-gradient-to-br from-indigo-600 via-indigo-900 to-slate-950 relative">
                                     <div class="absolute inset-0 bg-[url('https://www.transparenttextures.com/patterns/cubes.png')] opacity-20"></div>
                                     <!-- Badge -->
                                     <div class="absolute top-4 right-4 bg-slate-950/60 backdrop-blur-md border border-slate-800 text-white text-[9px] font-black px-3 py-1.5 rounded-full uppercase tracking-[0.15em] flex items-center gap-1.5 shadow-xl">
                                        <span class="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></span> Verified
                                     </div>
                                </div>

                                <!-- Profile Content -->
                                <div class="px-8 relative pt-20 pb-8">
                                     <!-- Avatar -->
                                     <div class="w-28 h-28 absolute -top-14 left-1/2 transform -translate-x-1/2 rounded-[2rem] border-8 border-slate-900 shadow-2xl overflow-hidden bg-slate-800 group-hover:rotate-3 transition-transform duration-500">
                                        <img src="uploads/profiles/<?=$w['profile_pic'] ? $w['profile_pic'] : 'default.png'?>" class="w-full h-full object-cover">
                                     </div>
                                     
                                     <div class="text-center">
                                        <h3 class="text-xl font-black text-white mb-1 truncate tracking-tight"><?=$w['full_name']?></h3>
                                        <div class="inline-flex items-center gap-2 mb-6 px-4 py-1.5 bg-indigo-500/10 rounded-full border border-indigo-500/20">
                                            <i data-lucide="<?= get_category_icon_name($w['job_category']) ?>" class="w-3.5 h-3.5 text-indigo-400"></i>
                                            <span class="text-indigo-400 font-black text-[10px] uppercase tracking-wider"><?=$w['job_category']?></span>
                                        </div>
                                        
                                        <div class="flex flex-col gap-3 mb-8">
                                            <div class="flex items-center justify-center text-slate-400 text-sm">
                                                <i data-lucide="map-pin" class="w-4 h-4 mr-2 text-indigo-500/50"></i>
                                                <span class="truncate font-medium"><?=$w['district']?></span>
                                            </div>
                                            <div class="flex items-center justify-center text-slate-400 text-sm">
                                                <i data-lucide="graduation-cap" class="w-4 h-4 mr-2 text-indigo-500/50"></i>
                                                <span class="truncate font-medium"><?=$w['qualification']?></span>
                                            </div>
                                        </div>

                                        <a href="worker_profile.php?id=<?=encrypt_id($w['employee_nic'])?>" class="flex items-center justify-center gap-2 w-full py-4 bg-slate-800 hover:bg-indigo-600 text-white font-black rounded-2xl transition-all duration-300 text-xs uppercase tracking-widest border border-slate-700 hover:border-indigo-500 shadow-lg hover:shadow-indigo-600/30">
                                            View Profile <i data-lucide="arrow-right" class="w-4 h-4"></i>
                                        </a>
                                     </div>
                                </div>
                            </div>
                        <?php endwhile; ?>
                    </div>
                <?php else: ?>
                    <div class="text-center py-32 bg-slate-900 rounded-[3rem] border border-slate-800 shadow-2xl relative overflow-hidden group">
                        <div class="absolute -top-24 -left-24 w-64 h-64 bg-indigo-600/5 rounded-full blur-3xl group-hover:bg-indigo-600/10 transition-colors"></div>
                        <div class="relative z-10">
                            <div class="inline-flex items-center justify-center w-24 h-24 rounded-3xl bg-slate-800 mb-6 border border-slate-700 shadow-inner">
                                <i data-lucide="search-x" class="w-12 h-12 text-slate-600"></i>
                            </div>
                            <h3 class="text-2xl font-black text-white mb-2 tracking-tight">No professionals found</h3>
                            <p class="text-slate-500 max-w-md mx-auto font-medium">We couldn't find anyone matching your specific criteria in this category.</p>
                            <a href="search.php" class="inline-flex items-center gap-2 mt-10 px-8 py-4 bg-indigo-600 text-white rounded-2xl hover:bg-indigo-500 transition shadow-xl shadow-indigo-600/30 font-black text-xs uppercase tracking-widest">
                                <i data-lucide="users" class="w-4 h-4"></i>
                                View All Workers
                            </a>
                        </div>
                    </div>
                <?php endif; ?>
            </main>
        </div>
    </div>

    <!-- Simple Footer -->
    <footer class="bg-slate-900 border-t border-slate-800 py-12 text-center text-slate-600 text-xs font-medium uppercase tracking-[0.2em]">
        <p>&copy; <?=date('Y')?> Work For Sri Lanka. All rights reserved.</p>
    </footer>

    <script>
        lucide.createIcons();

        // Divisional Secretariat Logic
        const districtData = <?= json_encode($all_districts) ?>;
        function updateDivisions() {
            const district = document.getElementById('district-select').value;
            const divisionSelect = document.getElementById('division-select');
            const currentDivision = "<?= $div ?>";
            
            divisionSelect.innerHTML = '<option value="" class="bg-slate-900">All Divisions</option>';
            
            if (district && districtData[district]) {
                districtData[district].forEach(d => {
                    const option = document.createElement('option');
                    option.value = d;
                    option.textContent = d;
                    option.className = 'bg-slate-900';
                    if (d === currentDivision) option.selected = true;
                    divisionSelect.appendChild(option);
                });
            }
        }
        
        // Initial call to populate divisions if district is already selected
        window.addEventListener('load', updateDivisions);
    </script>

</body>
</html>
