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

$emp_id = $_SESSION['user_id'];
$msg = '';

if(isset($_POST['post_job'])) {
    $title = sanitize_input($_POST['title']);
    $desc = sanitize_input($_POST['desc']);
    $cat = sanitize_input($_POST['category']);
    if($cat == 'Other') {
        $cat = sanitize_input($_POST['category_other']);
    }
    $loc = sanitize_input($_POST['location']);
    $stmt = $conn->prepare("INSERT INTO jobs (employer_id, title, description, category, location, status) VALUES (?, ?, ?, ?, ?, 'Pending')");
    $stmt->bind_param("issss", $emp_id, $title, $desc, $cat, $loc);
    $stmt->execute();
    $stmt->close();
    $msg = "Job posted successfully! It is now pending admin approval.";
}

if(isset($_POST['update_status'])) {
    $aid = intval($_POST['app_id']);
    $status = $_POST['status'];
    $stmt = $conn->prepare("UPDATE applications SET status = ? WHERE id = ?");
    $stmt->bind_param("si", $status, $aid);
    $stmt->execute();
    $stmt->close();
}

if(isset($_POST['delete_job'])) {
    $jid = intval($_POST['job_id']);
    // Verify ownership before deleting
    $check = $conn->query("SELECT id FROM jobs WHERE id=$jid AND employer_id=$emp_id");
    if($check->num_rows > 0) {
        $stmt = $conn->prepare("DELETE FROM jobs WHERE id=?");
        $stmt->bind_param("i", $jid);
        $stmt->execute();
        $stmt->close();
        $msg = "Job post deleted successfully.";
    }
}

$jobs = $conn->query("SELECT * FROM jobs WHERE employer_id = $emp_id ORDER BY created_at DESC");
$apps = $conn->query("SELECT a.*, j.title as job_title, ed.full_name, ed.employee_nic as worker_id, ed.profile_pic FROM applications a JOIN jobs j ON a.job_id = j.id JOIN employee_details ed ON a.employee_nic = ed.employee_nic WHERE j.employer_id = $emp_id ORDER BY a.created_at DESC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Employer 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);
        }
        @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>
                        <span class="text-xs font-normal text-white bg-indigo-600 px-2 py-0.5 rounded ml-2 align-middle">Employer</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"><?=$_SESSION['username']?></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="max-w-7xl mx-auto relative z-10">
            <h1 class="text-3xl font-bold mb-2 text-white">Manage Your Recruitment</h1>
            <p class="text-slate-400">Post new opportunities and review applications from skilled workers.</p>
        </div>
    </div>

    <!-- Main Content -->
    <div class="max-w-7xl mx-auto px-4 pb-20 pt-8">
        
        <?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 animate-fade-in-down">
                <i data-lucide="check-circle" class="w-5 h-5 mr-3 flex-shrink-0"></i>
                <span class="font-bold mr-2">Success!</span> <?=$msg?>
            </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            
            <!-- LEFT COLUMN: Post Job Form -->
            <div class="lg:col-span-1">
                <div class="glass-panel rounded-3xl shadow-xl overflow-hidden sticky top-24">
                    <div class="p-6 border-b border-slate-700/50 bg-slate-800/30">
                        <h2 class="text-lg font-bold text-white flex items-center">
                            <i data-lucide="plus-circle" class="w-5 h-5 mr-2 text-indigo-400"></i> Post a New Job
                        </h2>
                    </div>
                    <form method="post" class="p-6 space-y-4">
                        <div>
                            <label class="block text-xs font-bold text-slate-400 uppercase tracking-wide mb-1">Job Title</label>
                            <input type="text" name="title" required class="w-full px-4 py-3 rounded-xl form-input outline-none" placeholder="e.g. Skilled Carpenter Needed">
                        </div>
                        
                        <div>
                            <label class="block text-xs font-bold text-slate-400 uppercase tracking-wide mb-1">Category</label>
                            <select name="category" required onchange="toggleOther(this)" class="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();
                                foreach($categories as $category) {
                                    echo "<option value=\"$category\" class='bg-slate-900'>$category</option>";
                                }
                                ?>
                            </select>
                            <input type="text" name="category_other" id="cat_other_input" placeholder="Type Category" class="mt-2 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:none;">
                        </div>

                        <div>
                            <label class="block text-xs font-bold text-slate-400 uppercase tracking-wide mb-1">Location</label>
                            <input type="text" name="location" required class="w-full px-4 py-3 rounded-xl form-input outline-none" placeholder="City or Area">
                        </div>

                        <div>
                            <label class="block text-xs font-bold text-slate-400 uppercase tracking-wide mb-1">Description</label>
                            <textarea name="desc" required class="w-full px-4 py-3 rounded-xl form-input outline-none h-24 resize-none" placeholder="Describe the work required..."></textarea>
                        </div>

                        <button type="submit" name="post_job" class="w-full bg-indigo-600 hover:bg-indigo-500 text-white font-bold py-3.5 rounded-xl shadow-lg shadow-indigo-600/20 hover:shadow-indigo-600/40 transition transform active:scale-95 flex items-center justify-center">
                            Post Job Now
                        </button>
                    </form>
                </div>
            </div>

            <!-- RIGHT COLUMN: Applications & Jobs -->
            <div class="lg:col-span-2 space-y-8">
                
                <!-- Recent Applications -->
                <div class="glass-panel rounded-3xl shadow-xl overflow-hidden">
                    <div class="p-6 border-b border-slate-700/50 bg-slate-800/30 flex justify-between items-center">
                        <h2 class="text-lg font-bold text-white flex items-center">
                            <i data-lucide="users" class="w-5 h-5 mr-2 text-indigo-400"></i> Recent Applications
                        </h2>
                        <span class="bg-indigo-500/10 text-indigo-400 text-xs font-bold px-3 py-1 rounded-full border border-indigo-500/20"><?=$apps->num_rows?> Applicants</span>
                    </div>
                    
                    <div class="overflow-x-auto">
                        <?php if($apps->num_rows > 0): ?>
                        <table class="w-full text-left text-sm text-slate-300">
                            <thead class="bg-slate-800/50 text-slate-400 uppercase font-semibold text-xs tracking-wider">
                                <tr>
                                    <th class="px-6 py-4">Applicant</th>
                                    <th class="px-6 py-4">Applying For</th>
                                    <th class="px-6 py-4">Status</th>
                                    <th class="px-6 py-4 text-right">Action</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-700/50">
                                <?php while($a = $apps->fetch_assoc()): ?>
                                <tr class="hover:bg-slate-800/30 transition">
                                    <td class="px-6 py-4">
                                        <div class="flex items-center">
                                            <img src="../uploads/profiles/<?=$a['profile_pic'] ? $a['profile_pic'] : 'default.png'?>" class="h-10 w-10 rounded-full object-cover border-2 border-slate-600 shadow-sm mr-3">
                                            <div>
                                                <a href="../worker_profile.php?id=<?=encrypt_id($a['worker_id'])?>" class="font-bold text-white hover:text-indigo-400 transition" target="_blank"><?=$a['full_name']?></a>
                                                <div class="text-xs text-slate-500">Click to view profile</div>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 font-medium text-slate-300"><?=$a['job_title']?></td>
                                    <td class="px-6 py-4">
                                        <span class="px-2.5 py-1 rounded-lg text-xs font-bold 
                                            <?= $a['status'] == 'Accepted' ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 
                                               ($a['status'] == 'Rejected' ? 'bg-red-500/10 text-red-400 border border-red-500/20' : 
                                               ($a['status'] == 'Reviewing' ? 'bg-yellow-500/10 text-yellow-400 border border-yellow-500/20' : 'bg-slate-800 text-slate-400 border border-slate-700')) ?>">
                                            <?=$a['status']?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4 text-right">
                                        <div class="flex flex-col items-end gap-2">
                                            <form method="post" class="flex items-center bg-slate-800 rounded-lg p-1 border border-slate-700">
                                                <input type="hidden" name="app_id" value="<?=$a['id']?>">
                                                <select name="status" class="bg-transparent text-xs font-medium text-slate-300 outline-none border-none py-1 pl-2 pr-1 cursor-pointer">
                                                    <option value="Applied" class="bg-slate-900" <?=$a['status']=='Applied'?'selected':''?>>Pending</option>
                                                    <option value="Reviewing" class="bg-slate-900" <?=$a['status']=='Reviewing'?'selected':''?>>Reviewing</option>
                                                    <option value="Accepted" class="bg-slate-900" <?=$a['status']=='Accepted'?'selected':''?>>Accept</option>
                                                    <option value="Rejected" class="bg-slate-900" <?=$a['status']=='Rejected'?'selected':''?>>Reject</option>
                                                </select>
                                                <button type="submit" name="update_status" class="bg-slate-700 hover:bg-indigo-600 text-white rounded p-1 shadow-sm transition ml-1">
                                                    <i data-lucide="check" class="w-3 h-3"></i>
                                                </button>
                                            </form>
                                            <?php if($a['status'] == 'Accepted'): ?>
                                                <a href="rate_worker.php?worker_id=<?=$a['worker_id']?>&job_id=<?=$a['job_id']?>" class="text-xs text-orange-400 hover:text-orange-300 font-bold flex items-center transition">
                                                    <i data-lucide="star" class="w-3 h-3 mr-1"></i> Rate Worker
                                                </a>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                        <?php else: ?>
                            <div class="p-12 text-center text-slate-500 flex flex-col items-center">
                                <div class="bg-slate-800 p-4 rounded-full mb-3 border border-slate-700">
                                    <i data-lucide="inbox" class="w-8 h-8 text-slate-600"></i>
                                </div>
                                <p>No applications received yet.</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Active Jobs -->
                 <div class="glass-panel rounded-3xl shadow-xl overflow-hidden">
                    <div class="p-6 border-b border-slate-700/50 bg-slate-800/30">
                        <h2 class="text-lg font-bold text-white flex items-center">
                            <i data-lucide="briefcase" class="w-5 h-5 mr-2 text-indigo-400"></i> Your Posted Jobs
                        </h2>
                    </div>
                    <?php if($jobs->num_rows > 0): ?>
                        <div class="divide-y divide-slate-700/50">
                            <?php while($j = $jobs->fetch_assoc()): ?>
                            <div class="p-6 hover:bg-slate-800/30 transition flex justify-between items-center group">
                                <div>
                                    <h3 class="font-bold text-slate-200 group-hover:text-indigo-400 transition"><?=$j['title']?></h3>
                                    <div class="flex items-center text-xs text-slate-500 mt-1 gap-3">
                                        <span class="flex items-center"><i data-lucide="map-pin" class="w-3 h-3 mr-1"></i> <?=$j['location']?></span>
                                        <span class="flex items-center"><i data-lucide="tag" class="w-3 h-3 mr-1"></i> <?=$j['category']?></span>
                                        <span class="flex items-center"><i data-lucide="clock" class="w-3 h-3 mr-1"></i> <?=date('M d, Y', strtotime($j['created_at']))?></span>
                                    </div>
                                </div>
                                <div class="flex items-center gap-3">
                                    <?php
                                    $statusClass = 'bg-slate-800 text-slate-400 border border-slate-700';
                                    if($j['status'] == 'Open') $statusClass = 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20';
                                    if($j['status'] == 'Pending') $statusClass = 'bg-yellow-500/10 text-yellow-400 border border-yellow-500/20';
                                    if($j['status'] == 'Rejected') $statusClass = 'bg-red-500/10 text-red-400 border border-red-500/20';
                                    ?>
                                    <span class="<?=$statusClass?> text-xs font-bold px-3 py-1 rounded-full flex items-center"><?=$j['status']?></span>
                                    
                                    <form method="post" onsubmit="return confirm('Are you sure you want to delete this job post? This cannot be undone.');">
                                        <input type="hidden" name="job_id" value="<?=$j['id']?>">
                                        <button type="submit" name="delete_job" class="bg-red-500/10 hover:bg-red-500/20 text-red-400 p-1.5 rounded-lg transition border border-red-500/20" title="Delete Job">
                                            <i data-lucide="trash-2" class="w-4 h-4"></i>
                                        </button>
                                    </form>
                                </div>
                            </div>
                            <?php endwhile; ?>
                        </div>
                    <?php else: ?>
                        <div class="p-8 text-center text-slate-500 text-sm">You haven't posted any jobs yet.</div>
                    <?php endif; ?>
                </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();
        function toggleOther(select) {
            var input = document.getElementById('cat_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;
            }
        }
    </script>
</body>
</html>
