<?php
session_start();
include '../db_config.php';
include '../functions.php';
check_login();
check_role('employee');

$uid = $_SESSION['user_id'];
$nic = $_SESSION['username'];
$msg = '';
$error = '';

// Fetch existing details
$stmt = $conn->prepare("SELECT full_name, dob, qualification, job_category, phone, address, district, divisional_secretariat, experience, profile_pic, cv_file, gn_letter, gn_description, achievement_file, achievement_description, status FROM employee_details WHERE employee_nic=?");
$stmt->bind_param("s", $uid);
$stmt->execute();
$stmt->bind_result($fn, $dob, $q, $jc, $phone, $address, $district, $div_sec, $exp, $pic, $cv, $gn, $gn_desc, $ach_file, $ach_desc, $st);
$exists = $stmt->fetch();
$stmt->close();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $fn = sanitize_input($_POST['fn']);
    $dob = sanitize_input($_POST['dob']);
    $q = sanitize_input($_POST['q']);
    if($q == 'NVQ' && isset($_POST['nvq_level'])) {
        $q .= ' - ' . sanitize_input($_POST['nvq_level']);
    }
    $jc = sanitize_input($_POST['jc']);
    if($jc == 'Other') {
        $jc = sanitize_input($_POST['jc_other']);
    }
    $phone = sanitize_input($_POST['phone']);
    $address = sanitize_input($_POST['address']);
    $district = sanitize_input($_POST['district']);
    $div_sec = sanitize_input($_POST['divisional_secretariat']);
    $exp = sanitize_input($_POST['exp']);
    $gn_desc = sanitize_input($_POST['gn_desc']);
    $ach_desc = sanitize_input($_POST['ach_desc']);

    // Validation
    $validation_errors = [];
    if(empty($fn)) $validation_errors[] = "Full Name is required.";
    if(empty($dob)) $validation_errors[] = "Date of Birth is required.";
    if(empty($phone)) $validation_errors[] = "Phone Number is required.";
    if(empty($jc)) $validation_errors[] = "Job Category is required.";
    if(empty($district)) $validation_errors[] = "Preferred District is required.";
    if(empty($div_sec)) $validation_errors[] = "Divisional Secretariat is required.";
    if(empty($address)) $validation_errors[] = "Residential Address is required.";
    

    if (!empty($validation_errors)) {
        $error = implode("<br>", $validation_errors);
    } else {
        // Handle Profile Picture
        $pic_name = $pic;
        if (isset($_FILES['pic']) && $_FILES['pic']['error'] == 0) {
            $ext = pathinfo($_FILES['pic']['name'], PATHINFO_EXTENSION);
            $pic_name = "profile_" . $uid . "." . $ext;
            move_uploaded_file($_FILES['pic']['tmp_name'], "../uploads/profiles/" . $pic_name);
        }

        // Handle CV Upload
        $cv_name = $cv;
        if (isset($_FILES['cv']) && $_FILES['cv']['error'] == 0) {
            $ext = pathinfo($_FILES['cv']['name'], PATHINFO_EXTENSION);
            $cv_name = "cv_" . $uid . "." . $ext;
            if(!move_uploaded_file($_FILES['cv']['tmp_name'], "../uploads/cvs/" . $cv_name)) {
                $validation_errors[] = "Failed to upload CV. Please try again.";
            }
        } elseif (isset($_FILES['cv']) && $_FILES['cv']['error'] != UPLOAD_ERR_NO_FILE) {
            $validation_errors[] = "CV Upload Error. Code: " . $_FILES['cv']['error'];
        }

        // Handle GN Letter Upload
        $gn_name = $gn;
        if (isset($_FILES['gn_letter']) && $_FILES['gn_letter']['error'] == 0) {
            $target_dir = "../uploads/documents/";
            if (!is_dir($target_dir)) {
                mkdir($target_dir, 0777, true);
            }
            $ext = pathinfo($_FILES['gn_letter']['name'], PATHINFO_EXTENSION);
            $gn_name = "gn_letter_" . $uid . "." . $ext;
            if(!move_uploaded_file($_FILES['gn_letter']['tmp_name'], $target_dir . $gn_name)) {
                $validation_errors[] = "Failed to upload Documents. Please try again.";
            }
        }

        // Handle Achievement Upload
        $ach_name = $ach_file;
        if (isset($_FILES['achievement_file']) && $_FILES['achievement_file']['error'] == 0) {
            $target_dir = "../uploads/achievements/";
            if (!is_dir($target_dir)) {
                mkdir($target_dir, 0777, true);
            }
            $ext = pathinfo($_FILES['achievement_file']['name'], PATHINFO_EXTENSION);
            $ach_name = "achievement_" . $uid . "." . $ext;
            if(!move_uploaded_file($_FILES['achievement_file']['tmp_name'], $target_dir . $ach_name)) {
                $validation_errors[] = "Failed to upload Achievement file. Please try again.";
            }
        }

        if ($exists) {
            $stmt = $conn->prepare("UPDATE employee_details SET full_name=?, dob=?, qualification=?, job_category=?, phone=?, address=?, district=?, divisional_secretariat=?, experience=?, profile_pic=?, cv_file=?, gn_letter=?, gn_description=?, achievement_file=?, achievement_description=?, status='Pending' WHERE employee_nic=?");
            $stmt->bind_param("ssssssssssssssss", $fn, $dob, $q, $jc, $phone, $address, $district, $div_sec, $exp, $pic_name, $cv_name, $gn_name, $gn_desc, $ach_name, $ach_desc, $uid);
            $stmt->execute();
            $msg = "Profile updated and pending approval.";
        } else {
            $stmt = $conn->prepare("INSERT INTO employee_details (employee_nic, full_name, dob, qualification, job_category, phone, address, district, divisional_secretariat, experience, profile_pic, cv_file, gn_letter, gn_description, achievement_file, achievement_description, nic, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'Pending')");
            $stmt->bind_param("sssssssssssssssss", $uid, $fn, $dob, $q, $jc, $phone, $address, $district, $div_sec, $exp, $pic_name, $cv_name, $gn_name, $gn_desc, $ach_name, $ach_desc, $nic);
            $stmt->execute();
            $msg = "Profile submitted successfully.";
        }
        // Refresh local vars
        header("Location: dashboard.php?msg=" . urlencode($msg));
        exit();
    }
}

if (isset($_GET['msg'])) $msg = $_GET['msg'];

// Handle notification read
if(isset($_POST['mark_read'])) {
    $nid = intval($_POST['notif_id']);
    $stmt = $conn->prepare("UPDATE worker_notifications SET is_read = 1 WHERE id = ? AND employee_nic = ?");
    $stmt->bind_param("is", $nid, $uid);
    $stmt->execute();
    $stmt->close();
    header("Location: dashboard.php");
    exit();
}

// Handle hire status update
if(isset($_POST['update_hire_status'])) {
    $hid = intval($_POST['hire_id']);
    $new_status = sanitize_input($_POST['status']);
    $stmt = $conn->prepare("UPDATE customer_hires SET status = ? WHERE id = ? AND employee_nic = ?");
    $stmt->bind_param("sis", $new_status, $hid, $uid);
    $stmt->execute();
    $stmt->close();
    
    // Add notification for the customer if needed? (Future)
    header("Location: dashboard.php");
    exit();
}

// Fetch notifications
$stmt_notifs = $conn->prepare("SELECT * FROM worker_notifications WHERE employee_nic = ? ORDER BY created_at DESC LIMIT 10");
$stmt_notifs->bind_param("s", $uid);
$stmt_notifs->execute();
$notifs = $stmt_notifs->get_result();
$stmt_notifs->close();

// Fetch hire requests 
$stmt_hires = $conn->prepare("SELECT ch.*, c.phone, c.full_name as customer_name FROM customer_hires ch JOIN customers c ON ch.customer_id = c.id WHERE ch.employee_nic = ? ORDER BY ch.created_at DESC");
$stmt_hires->bind_param("s", $uid);
$stmt_hires->execute();
$hires = $stmt_hires->get_result();
$stmt_hires->close();
// Fetch Jobs
$jobs_res = $conn->query("SELECT j.*, ed.company_name FROM jobs j JOIN employer_details ed ON j.employer_id = ed.user_id WHERE j.status = 'Open' ORDER BY j.created_at DESC LIMIT 10");

// Fetch Customer Jobs
$cust_jobs_res = $conn->query("SELECT cj.*, c.full_name, c.phone FROM customer_jobs cj JOIN customers c ON cj.customer_id = c.id WHERE cj.status = 'open' ORDER BY cj.created_at DESC LIMIT 20");

// Handle Job Application in Dashboard
if(isset($_POST['apply_job'])) {
    if($st !== 'Approved') {
        $error = "Your account is pending approval. You cannot apply for jobs yet.";
    } else {
        $jid = intval($_POST['job_id']);
        $check = $conn->query("SELECT id FROM applications WHERE job_id = $jid AND employee_nic = '$uid'");
        if($check->num_rows == 0) {
            $conn->query("INSERT INTO applications (job_id, employee_nic) VALUES ($jid, '$uid')");
            $msg = "Application submitted!";
        } else {
            $error = "You have already applied for this job.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Worker Dashboard | 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; } 
        .glass-panel {
            background: rgba(30, 41, 59, 0.4);
            backdrop-filter: blur(12px);
            border: 1px solid rgba(255, 255, 255, 0.05);
        }
        .form-input {
            background: rgba(15, 23, 42, 0.6);
            border: 1px solid rgba(51, 65, 85, 1);
            color: white;
            transition: all 0.3s ease;
        }
        .form-input:focus {
            background: rgba(15, 23, 42, 0.9);
            border-color: #6366f1;
            box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.1);
        }
        .form-input:disabled {
            background: rgba(15, 23, 42, 0.3);
            color: #64748b;
            cursor: not-allowed;
        }
        @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);
        }
    </style>
</head>
<body class="bg-slate-950 min-h-screen 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="flex items-center gap-6">
                    <span class="text-sm font-medium text-slate-400 hidden md:inline">Logged in as: <span class="text-indigo-400 font-mono"><?=$nic?></span></span>
                    <a href="../logout.php" class="text-slate-400 hover:text-red-400 font-medium transition text-sm flex items-center">
                        <i data-lucide="log-out" class="w-4 h-4 mr-2"></i> Logout
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <!-- Header Section -->
    <div class="relative bg-slate-900 py-12 px-4 border-b border-slate-800 overflow-hidden">
        <div class="absolute top-0 right-0 w-[500px] h-[500px] bg-indigo-600/10 rounded-full blur-[100px] -mt-20 -mr-20 pointer-events-none"></div>
        <div class="absolute bottom-0 left-0 w-[300px] h-[300px] bg-emerald-600/5 rounded-full blur-[80px] -mb-10 -ml-10 pointer-events-none"></div>

        <div class="max-w-4xl mx-auto flex flex-col md:flex-row justify-between items-center gap-6 relative z-10">
            <div>
                <h1 class="text-3xl font-bold mb-2 text-white">Welcome Back, <span class="text-indigo-400"><?=$fn ? explode(' ', $fn)[0] : 'Worker'?></span></h1>
                <p class="text-slate-400 flex items-center gap-3">
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-bold uppercase tracking-wider
                        <?= ($st == 'Approved') ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 
                           (($st == 'Pending') ? 'bg-yellow-500/10 text-yellow-400 border border-yellow-500/20' : 
                           'bg-slate-700 text-slate-400') ?>">
                        <?= $st ? $st : 'N/A' ?>
                    </span>
                    <span class="text-sm opacity-80">Manage your profile and applications.</span>
                </p>
            </div>
            <div class="flex items-center gap-4">
                <div class="text-right hidden sm:block">
                    <p class="text-[10px] font-black text-slate-500 uppercase tracking-widest leading-none mb-1">Current Role</p>
                    <p class="text-xs font-bold text-indigo-400 uppercase tracking-wider">Verified Worker</p>
                </div>
                <div class="h-10 w-10 rounded-xl bg-indigo-500/10 flex items-center justify-center text-indigo-400 border border-indigo-500/20 shadow-lg">
                    <i data-lucide="user" class="w-5 h-5"></i>
                </div>
            </div>
        </div>
    </div>

    <div class="max-w-6xl mx-auto px-4 pb-20 pt-8">
        
        <!-- Tab Navigation -->
        <div class="flex flex-wrap gap-2 mb-8 bg-slate-900/50 p-1.5 rounded-2xl border border-slate-800 w-fit mx-auto md:mx-0">
            <button onclick="switchTab('jobs')" id="btn-jobs" class="tab-btn px-6 py-2.5 rounded-xl font-bold text-sm transition-all flex items-center gap-2">
                <i data-lucide="briefcase" class="w-4 h-4"></i> Company Jobs
            </button>
            <button onclick="switchTab('customer-jobs')" id="btn-customer-jobs" class="tab-btn px-6 py-2.5 rounded-xl font-bold text-sm transition-all flex items-center gap-2">
                <i data-lucide="user-check" class="w-4 h-4"></i> Customer Requests
            </button>
            <button onclick="switchTab('notifs')" id="btn-notifs" class="tab-btn px-6 py-2.5 rounded-xl font-bold text-sm transition-all flex items-center gap-2 relative">
                <i data-lucide="bell" class="w-4 h-4"></i> Notifications
                <?php 
                $unread = $conn->query("SELECT COUNT(*) as count FROM worker_notifications WHERE employee_nic = '$uid' AND is_read = 0")->fetch_assoc()['count'];
                if($unread > 0): 
                ?>
                    <span class="absolute -top-1 -right-1 w-4 h-4 bg-red-500 text-[8px] flex items-center justify-center rounded-full text-white border-2 border-slate-900"><?=$unread?></span>
                <?php endif; ?>
            </button>
            <button onclick="switchTab('profile')" id="btn-profile" class="tab-btn px-6 py-2.5 rounded-xl font-bold text-sm transition-all flex items-center gap-2">
                <i data-lucide="user-pen" class="w-4 h-4"></i> Update Profile
            </button>
        </div>

        <?php if($msg): ?>
            <div class="bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 px-6 py-4 rounded-xl mb-6 flex items-center shadow-sm">
                <i data-lucide="check-circle" class="w-6 h-6 mr-3 flex-shrink-0"></i>
                <?=$msg?>
            </div>
        <?php endif; ?>

        <?php if($error): ?>
            <div class="bg-red-500/10 border border-red-500/20 text-red-400 px-6 py-4 rounded-xl mb-6 flex items-center shadow-sm">
                <i data-lucide="alert-circle" class="w-6 h-6 mr-3 flex-shrink-0"></i>
                <div>
                    <strong>Please correct the following errors:</strong><br>
                    <span class="text-sm opacity-80"><?=$error?></span>
                </div>
            </div>
        <?php endif; ?>

        <!-- Tab: Browse Jobs -->
        <div id="tab-jobs" class="tab-content hidden animate-pop">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <?php if($jobs_res->num_rows > 0): ?>
                    <?php while($j = $jobs_res->fetch_assoc()): ?>
                        <div class="glass-panel p-6 rounded-3xl border border-slate-800 hover:border-indigo-500/30 transition group flex flex-col h-full shadow-lg">
                            <div class="flex-1">
                                <div class="flex justify-between items-start mb-4">
                                    <h3 class="text-xl font-bold text-white group-hover:text-indigo-400 transition"><?= $j['title'] ?></h3>
                                    <span class="text-[10px] font-black uppercase px-3 py-1 bg-slate-800 rounded-full text-slate-400 border border-slate-700"><?= $j['location'] ?></span>
                                </div>
                                <div class="flex items-center text-sm text-slate-500 mb-6 font-medium">
                                    <i data-lucide="building" class="w-4 h-4 mr-2 text-indigo-500/50"></i> <?= $j['company_name'] ?>
                                </div>
                                <p class="text-slate-400 text-sm mb-6 line-clamp-3 leading-relaxed"><?= $j['description'] ?></p>
                            </div>
                            <form method="post" class="mt-auto pt-4 border-t border-slate-800/50">
                                <input type="hidden" name="job_id" value="<?= $j['id'] ?>">
                                <button type="submit" name="apply_job" class="w-full py-3 bg-indigo-600 hover:bg-indigo-500 text-white font-bold rounded-xl transition shadow-lg shadow-indigo-600/20 flex items-center justify-center gap-2">
                                    Apply Now <i data-lucide="send" class="w-4 h-4"></i>
                                </button>
                            </form>
                        </div>
                    <?php endwhile; ?>
                <?php else: ?>
                    <div class="col-span-1 md:col-span-2 py-20 glass-panel rounded-3xl text-center">
                        <i data-lucide="search-x" class="w-12 h-12 text-slate-700 mx-auto mb-4"></i>
                        <p class="text-slate-500 font-medium">No open jobs found at the moment.</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Tab: Customer Jobs -->
        <div id="tab-customer-jobs" class="tab-content hidden animate-pop">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <?php if($cust_jobs_res->num_rows > 0): ?>
                    <?php while($cj = $cust_jobs_res->fetch_assoc()): ?>
                        <div class="glass-panel p-6 rounded-3xl border border-slate-800 hover:border-emerald-500/30 transition group flex flex-col h-full shadow-lg">
                            <div class="flex-1">
                                <div class="flex justify-between items-start mb-4">
                                    <h3 class="text-xl font-bold text-white group-hover:text-emerald-400 transition"><?= htmlspecialchars($cj['title']) ?></h3>
                                    <span class="text-[10px] font-black uppercase px-3 py-1 bg-slate-800 rounded-full text-slate-400 border border-slate-700"><?= htmlspecialchars($cj['district']) ?></span>
                                </div>
                                <div class="flex items-center text-sm text-slate-500 mb-2 font-medium">
                                    <i data-lucide="user" class="w-4 h-4 mr-2 text-emerald-500/50"></i> <?= htmlspecialchars($cj['full_name']) ?>
                                </div>
                                <div class="flex items-center text-sm text-slate-500 mb-6 font-medium">
                                    <i data-lucide="briefcase" class="w-4 h-4 mr-2 text-emerald-500/50"></i> Category: <?= htmlspecialchars($cj['category']) ?>
                                </div>
                                <p class="text-slate-400 text-sm mb-6 line-clamp-3 leading-relaxed"><?= nl2br(htmlspecialchars($cj['description'])) ?></p>
                            </div>
                            <div class="mt-auto pt-4 border-t border-slate-800/50 flex gap-2">
                                <a href="tel:<?= $cj['phone'] ?>" class="flex-1 py-3 bg-emerald-600 hover:bg-emerald-500 text-white font-bold rounded-xl transition shadow-lg shadow-emerald-600/20 flex items-center justify-center gap-2">
                                    <i data-lucide="phone" class="w-4 h-4"></i> Call Customer
                                </a>
                            </div>
                        </div>
                    <?php endwhile; ?>
                <?php else: ?>
                    <div class="col-span-1 md:col-span-2 py-20 glass-panel rounded-3xl text-center">
                        <i data-lucide="clipboard-x" class="w-12 h-12 text-slate-700 mx-auto mb-4"></i>
                        <p class="text-slate-500 font-medium">No customer requests found at the moment.</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <div id="tab-notifs" class="tab-content hidden animate-pop">
            <?php if($notifs && $notifs->num_rows > 0): ?>
                <div class="glass-panel rounded-3xl shadow-2xl overflow-hidden mb-8 border border-slate-800">
                    <div class="p-6 border-b border-slate-800 bg-indigo-600/10">
                        <h2 class="text-xl font-bold text-white flex items-center">
                            <i data-lucide="bell" class="w-5 h-5 mr-3 text-indigo-400"></i> Notifications
                        </h2>
                    </div>
                    <div class="p-2 space-y-1">
                        <?php while($n = $notifs->fetch_assoc()): ?>
                            <div class="p-4 rounded-2xl flex items-center justify-between transition group <?= $n['is_read'] ? 'bg-transparent opacity-60' : 'bg-slate-800/40 border border-slate-700/50' ?>">
                                <div class="flex items-center gap-4">
                                    <div class="w-10 h-10 rounded-xl flex items-center justify-center <?= $n['is_read'] ? 'bg-slate-800 text-slate-500' : 'bg-indigo-500/20 text-indigo-400' ?>">
                                        <i data-lucide="mail" class="w-5 h-5"></i>
                                    </div>
                                    <div>
                                        <p class="text-sm <?= $n['is_read'] ? 'text-slate-400' : 'text-white font-medium' ?> text-wrap"><?=$n['message']?></p>
                                        <span class="text-[10px] text-slate-500"><?= date('M d, Y h:i A', strtotime($n['created_at'])) ?></span>
                                    </div>
                                </div>
                                <?php if(!$n['is_read']): ?>
                                    <form method="post">
                                        <input type="hidden" name="notif_id" value="<?=$n['id']?>">
                                        <button type="submit" name="mark_read" class="p-2 hover:bg-slate-700 rounded-lg text-slate-400 hover:text-white transition" title="Mark as read">
                                            <i data-lucide="check" class="w-4 h-4"></i>
                                        </button>
                                    </form>
                                <?php endif; ?>
                            </div>
                        <?php endwhile; ?>
                    </div>
                </div>
            <?php else: ?>
                <div class="text-center py-20 glass-panel rounded-3xl border-dashed border-2 border-slate-800 mb-8">
                     <i data-lucide="bell-off" class="w-12 h-12 text-slate-800 mx-auto mb-4"></i>
                     <p class="text-slate-600 font-bold uppercase tracking-widest text-xs">No notifications yet</p>
                </div>
            <?php endif; ?>

            <!-- Hire Requests Section -->
            <div class="glass-panel rounded-3xl p-8 border border-slate-800">
                <h3 class="text-xl font-bold text-white mb-6 flex items-center justify-between">
                     Hire Requests (<?= $hires->num_rows ?>)
                     <i data-lucide="users" class="w-5 h-5 text-indigo-400"></i>
                </h3>
                <?php if($hires->num_rows > 0): ?>
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                        <?php while($h = $hires->fetch_assoc()): ?>
                            <div class="p-6 rounded-[2rem] bg-slate-800/40 border border-slate-700/50 hover:border-indigo-500/30 transition shadow-inner group">
                                <div class="flex justify-between items-start mb-4">
                                    <div class="text-xs font-bold text-white bg-slate-900/50 px-4 py-1.5 rounded-full border border-slate-700"><?= $h['customer_name'] ?></div>
                                    <span class="text-[9px] font-black uppercase tracking-widest px-3 py-1 rounded-full 
                                        <?= $h['status'] == 'Completed' ? 'bg-emerald-500/20 text-emerald-400' : 
                                           ($h['status'] == 'In Progress' ? 'bg-blue-500/20 text-blue-400' : 
                                           ($h['status'] == 'Cancelled' ? 'bg-red-500/20 text-red-400' : 'bg-indigo-500/20 text-indigo-400')) ?>">
                                        <?= $h['status'] ?>
                                    </span>
                                </div>
                                <p class="text-[10px] text-slate-500 mb-6 font-medium uppercase tracking-wider">Requested <?= date('M d, Y', strtotime($h['created_at'])) ?></p>
                                
                                <div class="flex flex-col gap-3">
                                    <?php if($h['status'] == 'Pending'): ?>
                                        <div class="grid grid-cols-2 gap-2">
                                            <form method="post">
                                                <input type="hidden" name="hire_id" value="<?=$h['id']?>">
                                                <input type="hidden" name="status" value="In Progress">
                                                <button type="submit" name="update_hire_status" class="w-full py-3 bg-emerald-600 hover:bg-emerald-500 text-white text-[10px] font-black uppercase tracking-widest rounded-xl transition shadow-lg active:scale-95 flex items-center justify-center gap-1.5">
                                                    <i data-lucide="check" class="w-3.5 h-3.5"></i> Accept
                                                </button>
                                            </form>
                                            <form method="post">
                                                <input type="hidden" name="hire_id" value="<?=$h['id']?>">
                                                <input type="hidden" name="status" value="Cancelled">
                                                <button type="submit" name="update_hire_status" class="w-full py-3 bg-slate-700 hover:bg-slate-600 text-white text-[10px] font-black uppercase tracking-widest rounded-xl transition shadow-lg active:scale-95 flex items-center justify-center gap-1.5">
                                                    <i data-lucide="x" class="w-3.5 h-3.5"></i> Decline
                                                </button>
                                            </form>
                                        </div>
                                    <?php elseif($h['status'] == 'In Progress'): ?>
                                        <div class="grid grid-cols-2 gap-2">
                                            <a href="../chat.php?hire_id=<?=$h['id']?>" class="py-3 bg-indigo-600 hover:bg-indigo-500 text-white text-[10px] font-black uppercase tracking-widest rounded-xl transition shadow-lg active:scale-95 flex items-center justify-center gap-1.5">
                                                <i data-lucide="message-square" class="w-3.5 h-3.5"></i> Chat
                                            </a>
                                            <a href="tel:<?= $h['phone'] ?>" class="py-3 bg-slate-800 hover:bg-slate-700 text-white text-[10px] font-black uppercase tracking-widest rounded-xl transition shadow-lg active:scale-95 flex items-center justify-center gap-1.5">
                                                <i data-lucide="phone" class="w-3.5 h-3.5"></i> Call
                                            </a>
                                        </div>
                                    <?php elseif($h['status'] == 'Completed'): ?>
                                         <a href="../chat.php?hire_id=<?=$h['id']?>" class="w-full py-3 bg-slate-900 border border-slate-700 hover:border-slate-500 text-slate-400 hover:text-white text-[10px] font-black uppercase tracking-widest rounded-xl transition shadow-lg active:scale-95 flex items-center justify-center gap-1.5">
                                            <i data-lucide="message-square" class="w-3.5 h-3.5"></i> Chat History
                                        </a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endwhile; ?>
                    </div>
                <?php else: ?>
                    <p class="text-center text-slate-500 py-10">No hire requests yet.</p>
                <?php endif; ?>
            </div>
        </div>

        <!-- Tab: Update Profile -->
        <div id="tab-profile" class="tab-content hidden animate-pop">
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
                 <!-- Profile Status & Quick Info -->
                <div class="lg:col-span-1 space-y-6">
                    <!-- Status Card -->
                    <div class="glass-panel rounded-3xl p-8 border-l-8 <?= ($st == 'Approved') ? 'border-l-emerald-500' : 'border-l-yellow-500' ?> shadow-2xl">
                        <h3 class="text-[10px] font-black text-slate-500 uppercase tracking-[0.2em] mb-6">Profile Status</h3>
                        <div class="flex flex-col items-center text-center gap-4">
                             <div class="w-20 h-20 rounded-[2rem] flex items-center justify-center <?= ($st == 'Approved') ? 'bg-emerald-500/10 text-emerald-400 shadow-[0_0_30px_rgba(16,185,129,0.2)]' : 'bg-yellow-500/10 text-yellow-400 shadow-[0_0_30px_rgba(234,179,8,0.2)]' ?> mb-2">
                                <i data-lucide="<?= ($st == 'Approved') ? 'shield-check' : 'clock' ?>" class="w-10 h-10"></i>
                            </div>
                            <div>
                                <p class="text-3xl font-black text-white uppercase tracking-tighter mb-1"><?= $st ? $st : 'Pending' ?></p>
                                <p class="text-[10px] font-bold text-slate-500 leading-relaxed max-w-[150px] uppercase tracking-widest mx-auto"><?= ($st == 'Approved') ? 'Profile Active' : 'Waiting' ?></p>
                            </div>
                        </div>
                    </div>

                    <!-- Contact Card -->
                    <div class="glass-panel rounded-3xl p-8 shadow-xl">
                         <h3 class="text-[10px] font-black text-slate-500 uppercase tracking-[0.2em] mb-6">Quick Overview</h3>
                         <div class="space-y-4">
                             <div class="flex items-center gap-4 p-4 bg-slate-800/50 rounded-2xl border border-slate-700/50">
                                 <i data-lucide="map-pin" class="w-5 h-5 text-indigo-400"></i>
                                 <div>
                                     <p class="text-[8px] text-slate-500 font-black uppercase">District</p>
                                     <p class="text-xs font-bold text-white"><?= $district ? $district : 'N/A' ?></p>
                                 </div>
                             </div>
                             <div class="flex items-center gap-4 p-4 bg-slate-800/50 rounded-2xl border border-slate-700/50">
                                 <i data-lucide="phone" class="w-5 h-5 text-indigo-400"></i>
                                 <div>
                                     <p class="text-[8px] text-slate-500 font-black uppercase">Phone</p>
                                     <p class="text-xs font-bold text-white"><?= $phone ? $phone : 'N/A' ?></p>
                                 </div>
                             </div>
                         </div>
                    </div>
                </div>

                <!-- Profile Form -->
                <div class="lg:col-span-2">
                    <div class="glass-panel rounded-3xl shadow-2xl overflow-hidden border border-slate-800">
                        <div class="p-8 border-b border-slate-800 bg-slate-900/40">
                            <h2 class="text-xl font-black text-white flex items-center gap-3">
                                <i data-lucide="settings" class="w-6 h-6 text-indigo-400"></i> Account Details
                            </h2>
                            <p class="text-[10px] font-bold text-slate-500 mt-2 uppercase tracking-widest leading-loose">Major changes require administrator verification.</p>
                        </div>
                        <form method="post" enctype="multipart/form-data" class="p-10 space-y-10">
                
                <!-- Profile Picture Section -->
                <div class="flex flex-col items-center justify-center p-6 bg-slate-800/30 rounded-2xl border-2 border-dashed border-slate-700 hover:border-indigo-500/50 transition group">
                     <?php if($pic): ?>
                        <img id="profilePreview" src="../uploads/profiles/<?=$pic?>?v=<?=time()?>" class="w-32 h-32 rounded-full object-cover border-4 border-slate-700 shadow-xl mb-4 group-hover:scale-110 transition">
                    <?php else: ?>
                        <img id="profilePreview" src="" style="display:none;" class="w-32 h-32 rounded-full object-cover border-4 border-slate-700 shadow-xl mb-4 group-hover:scale-110 transition">
                        <div id="defaultIcon" class="w-32 h-32 rounded-full bg-slate-800 flex items-center justify-center text-slate-600 mb-4 shadow-inner group-hover:text-indigo-400 transition">
                            <i data-lucide="camera" class="w-12 h-12"></i>
                        </div>
                    <?php endif; ?>
                    <label class="cursor-pointer bg-slate-700 hover:bg-indigo-600 px-4 py-2 rounded-lg text-sm font-medium text-white transition shadow-sm border border-transparent">
                        Change Photo <input type="file" name="pic" accept="image/*" class="hidden" onchange="previewImage(this)">
                    </label>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- Personal Info -->
                    <div class="space-y-5">
                        <label class="block">
                            <span class="text-sm font-semibold text-slate-400">Full Name</span>
                            <input type="text" name="fn" value="<?=$fn?>" required class="mt-2 block w-full px-4 py-3 rounded-xl form-input outline-none">
                        </label>
                        <label class="block">
                            <span class="text-sm font-semibold text-slate-400">NIC Number <span class="text-xs text-slate-600 font-normal">(Registered)</span></span>
                            <input type="text" value="<?=$nic?>" readonly class="mt-2 block w-full px-4 py-3 rounded-xl form-input disabled:opacity-50 cursor-not-allowed">
                        </label>
                        <label class="block">
                            <span class="text-sm font-semibold text-slate-400">Phone Number</span>
                            <div class="relative">
                                <span class="absolute left-4 top-5 text-slate-500"><i data-lucide="phone" class="w-4 h-4"></i></span>
                                <input type="text" name="phone" value="<?=$phone?>" required class="mt-2 block w-full pl-10 pr-4 py-3 rounded-xl form-input outline-none">
                            </div>
                        </label>
                        <label class="block">
                            <span class="text-sm font-semibold text-slate-400">Date of Birth</span>
                            <input type="date" name="dob" value="<?=$dob?>" required class="mt-2 block w-full px-4 py-3 rounded-xl form-input outline-none text-slate-300">
                        </label>
                    </div>

                    <!-- Professional Info -->
                    <div class="space-y-5">
                        <label class="block">
                            <span class="text-sm font-semibold text-slate-400">Qualification</span>
                            <?php 
                                $is_nvq = (strpos($q, 'NVQ') === 0); 
                                $nvq_val = '';
                                if($is_nvq) {
                                    $parts = explode(' - ', $q);
                                    if(count($parts) > 1) $nvq_val = $parts[1];
                                }
                            ?>
                            <select name="q" onchange="toggleNVQ(this)" class="mt-2 block w-full px-4 py-3 rounded-xl form-input outline-none appearance-none cursor-pointer">
                                <option value="NVQ" class="bg-slate-900" <?=$is_nvq?'selected':''?>>NVQ (Vocational)</option>
                                <option value="A/L" class="bg-slate-900" <?=$q=='A/L'?'selected':''?>>A/L (Advanced Level)</option>
                                <option value="O/L" class="bg-slate-900" <?=$q=='O/L'?'selected':''?>>O/L (Ordinary Level)</option>
                                <option value="Other" class="bg-slate-900" <?=$q=='Other'?'selected':''?>>Other</option>
                            </select>
                            <div id="nvq_level_div" style="display:<?=$is_nvq ? 'block' : 'none'?>;" class="mt-3">
                                <label class="block text-sm font-semibold text-slate-500 mb-2">NVQ Level</label>
                                <select name="nvq_level" id="nvq_level" class="w-full px-4 py-3 rounded-xl form-input outline-none appearance-none cursor-pointer">
                                    <option value="" class="bg-slate-900">Select NVQ Level</option>
                                    <option value="Level 3" class="bg-slate-900" <?=$nvq_val=='Level 3'?'selected':''?>>Level 3</option>
                                    <option value="Level 4" class="bg-slate-900" <?=$nvq_val=='Level 4'?'selected':''?>>Level 4</option>
                                    <option value="Level 5" class="bg-slate-900" <?=$nvq_val=='Level 5'?'selected':''?>>Level 5</option>
                                    <option value="Level 6" class="bg-slate-900" <?=$nvq_val=='Level 6'?'selected':''?>>Level 6</option>
                                    <option value="Level 7" class="bg-slate-900" <?=$nvq_val=='Level 7'?'selected':''?>>Level 7</option>
                                </select>
                            </div>
                        </label>

                        <label class="block">
                            <span class="text-sm font-semibold text-slate-400">Job Category</span>
                            <select name="jc" onchange="toggleOther(this)" required class="mt-2 block w-full px-4 py-3 rounded-xl form-input outline-none appearance-none cursor-pointer">
                                <?php
                                include_once '../categories.php';
                                $categories = get_job_categories();
                                $is_other = !in_array($jc, $categories) && !empty($jc);
                                foreach($categories as $category) {
                                    $selected = ($jc == $category || ($category == 'Other' && $is_other)) ? 'selected' : '';
                                    echo "<option value=\"$category\" class='bg-slate-900' $selected>$category</option>";
                                }
                                ?>
                            </select>
                            <input type="text" name="jc_other" id="jc_other_input" placeholder="Type your Job Category" value="<?=$is_other ? $jc : ''?>" class="mt-3 block w-full px-4 py-3 bg-slate-800 border border-slate-600 rounded-xl text-sm focus:border-indigo-500 transition outline-none text-white shadow-inner" style="display:<?=$is_other ? 'block' : 'none'?>;">
                        </label>
                    </div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 col-span-1 md:col-span-2">
                        <label class="block">
                            <span class="text-sm font-semibold text-slate-400">Preferred District</span>
                            <select name="district" id="district" onchange="loadDivisionalSecretariats()" required class="mt-2 block w-full px-4 py-3 rounded-xl form-input outline-none appearance-none cursor-pointer">
                                <option value="" class="bg-slate-900">Select District</option>
                                <?php
                                include_once '../districts.php';
                                $districts_data = get_districts();
                                foreach(array_keys($districts_data) as $d) {
                                    $selected = ($district == $d) ? 'selected' : '';
                                    echo "<option value=\"$d\" class='bg-slate-900' $selected>$d</option>";
                                }
                                ?>
                            </select>
                        </label>
                         <label class="block">
                            <span class="text-sm font-semibold text-slate-400">Divisional Secretariat</span>
                            <select name="divisional_secretariat" id="ds" required disabled class="mt-2 block w-full px-4 py-3 rounded-xl form-input outline-none appearance-none cursor-pointer disabled:opacity-50">
                                <option value="" class="bg-slate-900">Select DS Division</option>
                            </select>
                        </label>
                    </div>

                    <!-- Full Width Inputs -->
                    <div class="col-span-1 md:col-span-2 space-y-6">
                        <label class="block bg-slate-800/30 p-5 rounded-2xl border border-slate-700/50">
                            <span class="text-sm font-semibold text-slate-400 mb-3 block flex items-center"><i data-lucide="map-pin" class="w-4 h-4 mr-2"></i> Residential Address</span>
                            <textarea name="address" required placeholder="Type your full address here..." class="block w-full px-4 py-3 rounded-xl form-input outline-none h-24 resize-none"><?=$address?></textarea>
                        </label>
                        <label class="block">
                            <span class="text-sm font-semibold text-slate-400">Work Experience</span>
                            <textarea name="exp" class="mt-2 block w-full px-4 py-3 rounded-xl form-input outline-none h-32 resize-none" placeholder="Describe your past work..."><?=$exp?></textarea>
                        </label>
                        
                        <div class="bg-indigo-900/20 p-5 rounded-2xl border border-indigo-500/20 flex flex-col md:flex-row items-center justify-between gap-4">
                            <div>
                                <span class="text-sm font-bold text-indigo-400 block mb-1">CV / Resume (PDF)</span>
                                <?php if($cv): ?>
                                    <a href="../uploads/cvs/<?=$cv?>" target="_blank" class="text-xs text-slate-300 hover:text-white hover:underline flex items-center"><i data-lucide="file-text" class="w-3 h-3 mr-1"></i> View Current CV</a>
                                <?php else: ?>
                                    <span class="text-xs text-slate-500">No CV uploaded yet.</span>
                                <?php endif; ?>
                            </div>
                            <label class="cursor-pointer bg-slate-800 px-5 py-2.5 rounded-xl border border-slate-600 text-sm font-medium text-slate-300 hover:bg-indigo-600 hover:text-white hover:border-indigo-500 transition shadow-lg flex items-center">
                                <span id="cvFileName">Upload New</span>
                                <input type="file" name="cv" accept=".pdf" class="hidden" onchange="updateFileName(this, 'cvFileName')">
                            </label>
                        </div>

                        <div class="bg-indigo-900/10 p-6 rounded-2xl border border-indigo-500/10 space-y-4">
                            <div class="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
                                <div class="flex flex-col">
                                    <span class="text-sm font-bold text-indigo-400 mb-1">GN Letter / Relevant Docs</span>
                                    <?php if($gn): ?>
                                        <a href="../uploads/documents/<?=$gn?>" target="_blank" class="text-xs text-slate-300 hover:text-white hover:underline flex items-center"><i data-lucide="file-text" class="w-3 h-3 mr-1"></i> View Current Letter</a>
                                    <?php else: ?>
                                        <span class="text-xs text-slate-500">Not uploaded yet.</span>
                                    <?php endif; ?>
                                </div>
                                <label class="cursor-pointer bg-slate-800 px-5 py-2.5 rounded-xl border border-slate-600 text-sm font-medium text-slate-300 hover:bg-indigo-600 hover:text-white hover:border-indigo-500 transition shadow-lg flex items-center shrink-0">
                                    <span id="gnFileName">Upload New</span>
                                    <input type="file" name="gn_letter" accept=".pdf,image/*" class="hidden" onchange="updateFileName(this, 'gnFileName')">
                                </label>
                            </div>
                            <textarea name="gn_desc" placeholder="Describe the document you uploaded..." class="block w-full px-4 py-3 rounded-xl bg-slate-900/50 border border-slate-700/50 text-sm text-slate-300 focus:border-indigo-500 outline-none h-20 resize-none"><?=$gn_desc?></textarea>
                        </div>

                        <div class="bg-emerald-900/10 p-6 rounded-2xl border border-emerald-500/10 space-y-4">
                            <div class="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
                                <div class="flex flex-col">
                                    <span class="text-sm font-bold text-emerald-400 mb-1">Achievement / Award</span>
                                    <?php if($ach_file): ?>
                                        <a href="../uploads/achievements/<?=$ach_file?>" target="_blank" class="text-xs text-slate-300 hover:text-white hover:underline flex items-center"><i data-lucide="award" class="w-3 h-3 mr-1"></i> View Achievement</a>
                                    <?php else: ?>
                                        <span class="text-xs text-slate-500">Not uploaded yet.</span>
                                    <?php endif; ?>
                                </div>
                                <label class="cursor-pointer bg-slate-800 px-5 py-2.5 rounded-xl border border-slate-600 text-sm font-medium text-slate-300 hover:bg-emerald-600 hover:text-white hover:border-emerald-500 transition shadow-lg flex items-center shrink-0">
                                    <span id="achFileName">Upload File</span>
                                    <input type="file" name="achievement_file" accept=".pdf,image/*" class="hidden" onchange="updateFileName(this, 'achFileName')">
                                </label>
                            </div>
                            <textarea name="ach_desc" placeholder="Describe your achievement or award..." class="block w-full px-4 py-3 rounded-xl bg-slate-900/50 border border-slate-700/50 text-sm text-slate-300 focus:border-emerald-500 outline-none h-20 resize-none"><?=$ach_desc?></textarea>
                        </div>
                    </div>
                </div>

                <div class="pt-8 border-t border-slate-700/50 flex justify-end">
                    <?php if($st != 'Approved'): ?>
                        <button type="submit" class="bg-indigo-600 hover:bg-indigo-500 text-white px-8 py-3.5 rounded-xl font-bold shadow-lg shadow-indigo-600/20 hover:shadow-indigo-600/40 transition transform active:scale-95 flex items-center">
                            <i data-lucide="save" class="w-5 h-5 mr-2"></i> Update Profile
                        </button>
                    <?php else: ?>
                        <div class="flex flex-col items-end">
                             <p class="text-xs text-slate-500 mb-2 italic">Profile verified. Major changes require approval.</p>
                             <button type="submit" class="bg-slate-700 hover:bg-slate-600 text-white px-8 py-3.5 rounded-xl font-bold shadow-lg transition flex items-center">
                                <i data-lucide="save" class="w-5 h-5 mr-2"></i> Update Info
                            </button>
                        </div>
                    <?php endif; ?>
                </div>

            </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Simple Footer -->
    <footer class="bg-slate-900 border-t border-slate-800 py-8 text-center text-slate-500 text-sm mt-12">
        <p>&copy; <?=date('Y')?> Work For Sri Lanka. All rights reserved.</p>
    </footer>

    <script>
        lucide.createIcons();
        
        // Pass PHP array to JS
        const districtsData = <?php echo json_encode($districts_data); ?>;
        const currentDivSec = "<?=$div_sec?>";

        function toggleNVQ(select) {
            var div = document.getElementById('nvq_level_div');
            var input = document.getElementById('nvq_level');
            if(select.value === 'NVQ') {
                div.style.display = 'block';
                input.required = true;
            } else {
                div.style.display = 'none';
                input.required = false;
                input.value = '';
            }
        }

        function toggleOther(select) {
            var input = document.getElementById('jc_other_input');
            if(select.value === 'Other') {
                input.style.display = 'block';
                input.required = true;
                setTimeout(() => input.focus(), 100);
            } else {
                input.style.display = 'none';
                input.required = false;
            }
        }
        
        function updateFileName(input, spanId) {
            if(input.files && input.files.length > 0) {
                document.getElementById(spanId).innerText = input.files[0].name;
            } else {
                document.getElementById(spanId).innerText = "Upload New";
            }
        }
        function previewImage(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    var img = document.getElementById('profilePreview');
                    var icon = document.getElementById('defaultIcon');
                    img.src = e.target.result;
                    img.style.display = 'block';
                    if(icon) icon.style.display = 'none';
                }
                reader.readAsDataURL(input.files[0]);
            }
        }

        function loadDivisionalSecretariats(preselect = null) {
            const districtSelect = document.getElementById('district');
            const dsSelect = document.getElementById('ds');
            const selectedDistrict = districtSelect.value;

            // Reset DS dropdown
            dsSelect.innerHTML = '<option value="" class="bg-slate-900">Select DS Division</option>';
            dsSelect.disabled = true;

            if (selectedDistrict && districtsData[selectedDistrict]) {
                districtsData[selectedDistrict].forEach(ds => {
                    const option = document.createElement('option');
                    option.value = ds;
                    option.textContent = ds;
                    option.className = 'bg-slate-900';
                    dsSelect.appendChild(option);
                    
                    if(ds == preselect) {
                        dsSelect.value = ds;
                    }
                });
                dsSelect.disabled = false;
                
                // If preselect is passed, try to set it
                if(preselect) dsSelect.value = preselect;
            }
        }

        // Tab Switching Logic
        function switchTab(tabId) {
            // Hide all contents
            document.querySelectorAll('.tab-content').forEach(c => c.classList.add('hidden'));
            // Remove active styles from all buttons
            document.querySelectorAll('.tab-btn').forEach(b => {
                b.classList.remove('bg-indigo-600', 'text-white', 'shadow-lg', 'shadow-indigo-600/20');
                b.classList.add('text-slate-400', 'hover:text-white', 'hover:bg-slate-800');
            });

            // Show target content
            document.getElementById('tab-' + tabId).classList.remove('hidden');
            // Active style for target button
            const activeBtn = document.getElementById('btn-' + tabId);
            activeBtn.classList.add('bg-indigo-600', 'text-white', 'shadow-lg', 'shadow-indigo-600/20');
            activeBtn.classList.remove('text-slate-400', 'hover:text-white', 'hover:bg-slate-800');
            
            // Save preference
            localStorage.setItem('activeWorkerTab', tabId);
        }

        // Initialize tabs on load
        window.addEventListener('load', () => {
            const lastTab = localStorage.getItem('activeWorkerTab') || 'jobs';
            switchTab(lastTab);
            
            loadDivisionalSecretariats(currentDivSec);
        });
    </script>
</body>
</html>
