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

check_login();
check_role('admin');

$nic = isset($_GET['id']) ? sanitize_input($_GET['id']) : '';
$msg = '';
$error = '';

if(!$nic) {
    header("Location: manage_employees.php");
    exit();
}

// Handle Update
if(isset($_POST['update'])) {
    $full_name = sanitize_input($_POST['full_name']);
    $phone = sanitize_input($_POST['phone']);
    $job_category = sanitize_input($_POST['job_category']);
    $status = sanitize_input($_POST['status']);
    $district = sanitize_input($_POST['district']);
    $div_sec = sanitize_input($_POST['divisional_secretariat']);
    $qualification = sanitize_input($_POST['qualification']);
    if($qualification == 'NVQ' && isset($_POST['nvq_level'])) {
        $qualification .= ' - ' . sanitize_input($_POST['nvq_level']);
    }
    
    // Update employee_details
    $stmt = $conn->prepare("UPDATE employee_details SET full_name=?, phone=?, job_category=?, status=?, district=?, divisional_secretariat=?, qualification=? WHERE employee_nic=?");
    $stmt->bind_param("ssssssss", $full_name, $phone, $job_category, $status, $district, $div_sec, $qualification, $nic);
    
    if($stmt->execute()) {
        $msg = "Employee details updated successfully.";
        
        // Handle Password Reset
        if(!empty($_POST['reset_password'])) {
            $new_pass = password_hash($_POST['reset_password'], PASSWORD_DEFAULT);
            $up_pass = $conn->prepare("UPDATE employee_login SET password=? WHERE nic=?");
            $up_pass->bind_param("ss", $new_pass, $nic);
            if($up_pass->execute()) {
                $msg .= " Password has been reset.";
            }
        }
    } else {
        $error = "Error updating details.";
    }
}

// Fetch current details
$stmt = $conn->prepare("SELECT * FROM employee_details WHERE employee_nic=?");
$stmt->bind_param("s", $nic);
$stmt->execute();
$result = $stmt->get_result();
$employee = $result->fetch_assoc();

if(!$employee) {
    $error = "Employee details not found (User might not have completed profile yet).";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Employee | Admin Panel</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);
        }
    </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">
                <a href="<?= BASE_URL ?>/index.php" class="text-2xl font-bold italic tracking-tighter text-white">
                    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">Admin Panel</span>
                </a>
                <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 -->
    <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-[400px] h-[400px] bg-red-600/10 rounded-full blur-[90px] -mt-20 -mr-20 pointer-events-none"></div>

        <div class="max-w-4xl mx-auto flex flex-col md:flex-row justify-between items-center gap-4 relative z-10">
            <div>
                <h1 class="text-3xl font-bold mb-2 text-white">Edit Employee</h1>
                <p class="text-slate-400">Update details for NIC: <span class="font-mono text-indigo-400"><?=$nic?></span></p>
            </div>
            <a href="manage_employees.php" class="bg-slate-800 hover:bg-slate-700 text-white px-5 py-2.5 rounded-xl font-bold transition flex items-center shadow-lg border border-slate-700 text-sm">
                <i data-lucide="arrow-left" class="w-4 h-4 mr-2"></i> Back to List
            </a>
        </div>
    </div>

    <!-- Main Content -->
    <div class="max-w-4xl 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; ?>

        <?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 animate-fade-in-down">
                <i data-lucide="alert-circle" class="w-5 h-5 mr-3 flex-shrink-0"></i>
                <span class="font-bold mr-2">Error:</span> <?=$error?>
            </div>
        <?php endif; ?>

        <?php if($employee): ?>
        <div class="glass-panel rounded-3xl shadow-2xl overflow-hidden animate-fade-in-up">
            <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="edit" class="w-5 h-5 mr-2 text-indigo-400"></i> Update Information
                </h2>
            </div>
            
            <form method="post" class="p-8 space-y-6">
                <input type="hidden" name="update" value="1">
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-sm font-bold text-slate-400 mb-2">Full Name</label>
                        <input type="text" name="full_name" value="<?=$employee['full_name']?>" class="w-full px-4 py-3 rounded-xl form-input outline-none">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-bold text-slate-400 mb-2">Phone Number</label>
                        <input type="text" name="phone" value="<?=$employee['phone']?>" class="w-full px-4 py-3 rounded-xl form-input outline-none">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-bold text-slate-400 mb-2">Job Category</label>
                        <select name="job_category" class="w-full px-4 py-3 rounded-xl form-input outline-none appearance-none cursor-pointer">
                            <option value="<?=$employee['job_category']?>" class="bg-slate-900"><?=$employee['job_category']?> (Current)</option>
                            <?php
                            include_once '../categories.php';
                            $cats = get_job_categories();
                            foreach($cats as $c) {
                                echo "<option value='$c' class='bg-slate-900'>$c</option>";
                            }
                            ?>
                        </select>
                    </div>

                    <div>
                         <?php 
                            $q = $employee['qualification'];
                            $is_nvq = (strpos($q, 'NVQ') === 0); 
                            $nvq_val = '';
                            if($is_nvq) {
                                $parts = explode(' - ', $q);
                                if(count($parts) > 1) $nvq_val = $parts[1];
                            }
                        ?>
                        <label class="block text-sm font-bold text-slate-400 mb-2">Qualification</label>
                        <select name="qualification" onchange="toggleNVQ(this)" class="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>
                    </div>

                    <div>
                        <label class="block text-sm font-bold text-slate-400 mb-2">District</label>
                        <select name="district" id="district" required onchange="loadDivisionalSecretariats()" class="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) {
                                $sel = ($employee['district'] == $d) ? 'selected' : '';
                                echo "<option value='$d' class='bg-slate-900' $sel>$d</option>";
                            }
                            ?>
                        </select>
                    </div>

                    <div>
                        <label class="block text-sm font-bold text-slate-400 mb-2">Divisional Secretariat</label>
                        <select name="divisional_secretariat" id="ds" required class="w-full px-4 py-3 rounded-xl form-input outline-none appearance-none cursor-pointer disabled:opacity-50">
                             <!-- Populated by JS -->
                             <option value="<?=$employee['divisional_secretariat']?>" class="bg-slate-900"><?=$employee['divisional_secretariat']?></option>
                        </select>
                    </div>

                    <div class="md:col-span-2">
                        <label class="block text-sm font-bold text-slate-400 mb-2">Account Status</label>
                        <div class="flex flex-col sm:flex-row gap-4">
                            <label class="flex items-center gap-3 cursor-pointer bg-slate-800/50 px-5 py-3 rounded-xl border border-slate-700 hover:border-emerald-500/50 transition w-full group">
                                <input type="radio" name="status" value="Approved" <?=$employee['status']=='Approved'?'checked':''?> class="w-4 h-4 text-emerald-500 focus:ring-emerald-500 bg-slate-900 border-slate-600">
                                <span class="text-sm font-medium text-slate-300 group-hover:text-emerald-400 transition">Approved</span>
                            </label>
                            <label class="flex items-center gap-3 cursor-pointer bg-slate-800/50 px-5 py-3 rounded-xl border border-slate-700 hover:border-yellow-500/50 transition w-full group">
                                <input type="radio" name="status" value="Pending" <?=$employee['status']=='Pending'?'checked':''?> class="w-4 h-4 text-yellow-500 focus:ring-yellow-500 bg-slate-900 border-slate-600">
                                <span class="text-sm font-medium text-slate-300 group-hover:text-yellow-400 transition">Pending</span>
                            </label>
                            <label class="flex items-center gap-3 cursor-pointer bg-slate-800/50 px-5 py-3 rounded-xl border border-slate-700 hover:border-red-500/50 transition w-full group">
                                <input type="radio" name="status" value="Rejected" <?=$employee['status']=='Rejected'?'checked':''?> class="w-4 h-4 text-red-500 focus:ring-red-500 bg-slate-900 border-slate-600">
                                <span class="text-sm font-medium text-slate-300 group-hover:text-red-400 transition">Rejected</span>
                            </label>
                        </div>
                    </div>

                    <div class="md:col-span-2 border-t border-slate-700/50 pt-6 mt-2">
                         <h3 class="text-sm font-bold text-slate-200 mb-4 flex items-center"><i data-lucide="lock" class="w-4 h-4 mr-2 text-red-400"></i> Security</h3>
                         <label class="block text-sm font-bold text-slate-400 mb-2">Reset Password <span class="text-xs font-normal text-slate-500">(Leave empty to keep current)</span></label>
                         <input type="text" name="reset_password" class="w-full px-4 py-3 bg-red-900/10 border border-red-500/20 rounded-xl text-sm focus:border-red-500 transition outline-none placeholder-red-400/30 text-red-400" placeholder="Enter new password to force reset">
                    </div>
                </div>

                <div class="pt-8 border-t border-slate-700/50 flex justify-end">
                    <button type="submit" class="bg-indigo-600 hover:bg-indigo-500 text-white px-8 py-3 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> Save Changes
                    </button>
                </div>
            </form>
        </div>
        <?php endif; ?>
    </div>

    <!-- 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 = "<?=$employee['divisional_secretariat']?>";

        function loadDivisionalSecretariats(preselect = null) {
            const districtSelect = document.getElementById('district');
            const dsSelect = document.getElementById('ds');
            const selectedDistrict = districtSelect.value;
            
            // Preserve current value if not changing functionality
            const currentVal = dsSelect.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';
                    
                    if(preselect && ds === preselect) {
                        option.selected = true;
                    } else if (ds === currentVal) {
                         option.selected = true;
                    }

                    dsSelect.appendChild(option);
                });
                dsSelect.disabled = false;
            }
        }

        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 = '';
            }
        }
        
        // Init
        document.addEventListener('DOMContentLoaded', () => {
             // Only load if district is selected and we need to populate
            if(document.getElementById('district').value) {
                loadDivisionalSecretariats(currentDivSec); 
            }
        });
    </script>
</body>
</html>
