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

check_login();
check_role('dme');

$msg = "";
$error = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $nic = sanitize_input($_POST['nic']);
    $password = $_POST['password'];
    $full_name = sanitize_input($_POST['full_name']);
    $dob = sanitize_input($_POST['dob']);
    
    $phone = sanitize_input($_POST['phone']);
    $address = sanitize_input($_POST['address']);
    
    $qualification = sanitize_input($_POST['qualification']);
    if($qualification == 'NVQ' && isset($_POST['nvq_level'])) {
        $qualification .= ' - ' . sanitize_input($_POST['nvq_level']);
    }
    $job_category = sanitize_input($_POST['job_category']);
    if($job_category == 'Other') {
        $job_category = sanitize_input($_POST['job_category_other']);
    }
    $district = sanitize_input($_POST['district']);
    $div_sec = sanitize_input($_POST['divisional_secretariat']);
    
    // Check if NIC exists
    $check = $conn->prepare("SELECT nic FROM employee_login WHERE nic = ?");
    $check->bind_param("s", $nic);
    $check->execute();
    $check->store_result();
    if($check->num_rows > 0) {
        $error = "Employee with this NIC already exists.";
    }
    
    // Handle Profile Picture Upload
    $profile_pic_name = "";
    if(isset($_FILES['profile_pic']) && $_FILES['profile_pic']['error'] == 0) {
        $target_dir = "../uploads/profiles/";
        if (!is_dir($target_dir)) {
            mkdir($target_dir, 0777, true);
        }
        $file_ext = pathinfo($_FILES["profile_pic"]["name"], PATHINFO_EXTENSION);
        $profile_pic_name = "profile_" . $nic . "." . $file_ext;
        $target_file = $target_dir . $profile_pic_name;
        
        if(!move_uploaded_file($_FILES["profile_pic"]["tmp_name"], $target_file)) {
            $error = "Sorry, there was an error uploading your file.";
        }
    } else {
        $error = "Profile picture is required.";
    }
    
    // Insert into db
    if(empty($error)) {
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        
        $conn->begin_transaction();
        try {
            // 1. Insert Login
            $stmt1 = $conn->prepare("INSERT INTO employee_login (nic, password, role) VALUES (?, ?, 'employee')");
            $stmt1->bind_param("ss", $nic, $hashed_password);
            $stmt1->execute();
            $stmt1->close();
            
            // 2. Insert Details
            $stmt2 = $conn->prepare("INSERT INTO employee_details (employee_nic, full_name, dob, qualification, job_category, district, divisional_secretariat, phone, address, profile_pic, nic, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'Approved')");
            $stmt2->bind_param("sssssssssss", $nic, $full_name, $dob, $qualification, $job_category, $district, $div_sec, $phone, $address, $profile_pic_name, $nic);
            $stmt2->execute();
            $stmt2->close();
            
            $conn->commit();
            $msg = "Employee registered successfully!";
            // Reset fields
            $nic = $full_name = $dob = $phone = $address = $qualification = $job_category = $district = $div_sec = "";
        } catch (Exception $e) {
            $conn->rollback();
            $error = "Registration failed: " . $e->getMessage();
        }
    }
    $check->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Employee | DME Portal</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">DME 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 Section -->
    <div class="relative bg-slate-900 py-12 px-4 border-b border-slate-800 overflow-hidden">
        <div class="absolute top-0 left-0 w-[400px] h-[400px] bg-indigo-600/10 rounded-full blur-[90px] -mt-20 -ml-20 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">Register New Employee</h1>
                <p class="text-slate-400">Create a new worker account and verify their details instantly.</p>
            </div>
            <a href="dashboard.php" class="bg-slate-800 hover:bg-slate-700 text-white px-6 py-3 rounded-xl font-bold transition flex items-center shadow-lg border border-slate-700">
                <i data-lucide="arrow-left" class="w-5 h-5 mr-2"></i> Back to Dashboard
            </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; ?>

        <div class="glass-panel rounded-3xl shadow-2xl overflow-hidden">
            <div class="p-8 border-b border-slate-700/50 bg-slate-800/30">
                <h2 class="text-lg font-bold text-white flex items-center">
                    <i data-lucide="user-plus" class="w-5 h-5 mr-2 text-emerald-400"></i> Worker Details Form
                </h2>
                <p class="text-xs text-slate-400 mt-1">Please ensure all NIC details match the physical ID card.</p>
            </div>
            
            <form action="" method="post" enctype="multipart/form-data" class="p-8 space-y-8">
                
                <!-- Section: Account Credentials -->
                <div>
                    <h3 class="text-xs font-bold text-indigo-400 uppercase tracking-widest mb-6 pb-2 border-b border-slate-700/50">Account Credentials</h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label class="block text-sm font-semibold text-slate-300 mb-2">NIC Number <span class="text-red-400">*</span></label>
                            <div class="relative">
                                <span class="absolute left-4 top-3.5 text-slate-500"><i data-lucide="credit-card" class="w-4 h-4"></i></span>
                                <input type="text" name="nic" required placeholder="Ex: 200012345678" class="w-full pl-11 pr-4 py-3 rounded-xl form-input outline-none">
                            </div>
                            <p class="text-xs text-slate-500 mt-2 ml-1">This will be the username.</p>
                        </div>
                        <div>
                            <label class="block text-sm font-semibold text-slate-300 mb-2">Assign Password <span class="text-red-400">*</span></label>
                            <div class="relative">
                                <span class="absolute left-4 top-3.5 text-slate-500"><i data-lucide="lock" class="w-4 h-4"></i></span>
                                <input type="text" name="password" required placeholder="Ex: password123" class="w-full pl-11 pr-4 py-3 rounded-xl form-input outline-none">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Section: Personal Info -->
                 <div>
                    <h3 class="text-xs font-bold text-indigo-400 uppercase tracking-widest mb-6 pb-2 border-b border-slate-700/50">Personal Information</h3>
                    
                    <!-- Profile Picture -->
                    <div class="mb-8 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">
                        <img id="preview" src="" class="hidden w-24 h-24 rounded-full object-cover border-4 border-slate-600 shadow-md mb-3">
                        <div id="placeholder" class="w-24 h-24 rounded-full bg-slate-800 flex items-center justify-center text-slate-500 mb-3 group-hover:text-indigo-400 transition">
                            <i data-lucide="camera" class="w-8 h-8"></i>
                        </div>
                        <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">
                            Upload Photo <span class="text-red-400">*</span> <input type="file" name="profile_pic" required accept="image/*" class="hidden" onchange="previewImage(this)">
                        </label>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div class="md:col-span-2">
                            <label class="block text-sm font-semibold text-slate-300 mb-2">Full Name <span class="text-red-400">*</span></label>
                            <input type="text" name="full_name" required placeholder="Ex: John Doe" class="w-full px-4 py-3 rounded-xl form-input outline-none">
                        </div>
                        <div>
                            <label class="block text-sm font-semibold text-slate-300 mb-2">Date of Birth <span class="text-red-400">*</span></label>
                            <input type="date" name="dob" required class="w-full px-4 py-3 rounded-xl form-input outline-none text-slate-300">
                        </div>
                         <div>
                            <label class="block text-sm font-semibold text-slate-300 mb-2">Phone Number <span class="text-red-400">*</span></label>
                            <input type="text" name="phone" required placeholder="07XXXXXXXX" class="w-full px-4 py-3 rounded-xl form-input outline-none">
                        </div>
                        
                        <div class="md:col-span-2">
                            <label class="block text-sm font-semibold text-slate-300 mb-2">Address <span class="text-red-400">*</span></label>
                            <textarea name="address" required rows="2" class="w-full px-4 py-3 rounded-xl form-input outline-none"></textarea>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-semibold text-slate-300 mb-2">Residential District <span class="text-red-400">*</span></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) {
                                    echo "<option value=\"$d\" class='bg-slate-900'>$d</option>";
                                }
                                ?>
                            </select>
                        </div>
                        <div>
                           <label class="block text-sm font-semibold text-slate-300 mb-2">Divisional Secretariat <span class="text-red-400">*</span></label>
                           <select name="divisional_secretariat" id="ds" required disabled class="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>
                       </div>
                    </div>
                </div>

                <!-- Section: Professional Info -->
                 <div>
                    <h3 class="text-xs font-bold text-indigo-400 uppercase tracking-widest mb-6 pb-2 border-b border-slate-700/50">Professional Details</h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label class="block text-sm font-semibold text-slate-300 mb-2">Qualification <span class="text-red-400">*</span></label>
                            <select name="qualification" required onchange="toggleNVQ(this)" class="w-full px-4 py-3 rounded-xl form-input outline-none appearance-none cursor-pointer">
                                <option value="" class="bg-slate-900">Select Qualification</option>
                                <option value="NVQ" class="bg-slate-900">NVQ (Vocational)</option>
                                <option value="A/L" class="bg-slate-900">A/L</option>
                                <option value="O/L" class="bg-slate-900">O/L</option>
                                <option value="Other" class="bg-slate-900">Other</option>
                            </select>
                            <div id="nvq_level_div" style="display:none;" class="mt-3">
                                <label class="block text-sm font-semibold text-slate-400 mb-2">NVQ Level <span class="text-red-400">*</span></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">Level 3</option>
                                    <option value="Level 4" class="bg-slate-900">Level 4</option>
                                    <option value="Level 5" class="bg-slate-900">Level 5</option>
                                    <option value="Level 6" class="bg-slate-900">Level 6</option>
                                    <option value="Level 7" class="bg-slate-900">Level 7</option>
                                </select>
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-semibold text-slate-300 mb-2">Job Category <span class="text-red-400">*</span></label>
                            <select name="job_category" required onchange="toggleOther(this)" class="w-full px-4 py-3 rounded-xl form-input outline-none appearance-none cursor-pointer">
                                <option value="" class="bg-slate-900">Select Category</option>
                                <?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="job_category_other" id="jc_other_input" placeholder="Type specific job category" class="mt-3 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>
                </div>

                <div class="pt-8 border-t border-slate-700/50 flex justify-end">
                    <button type="submit" class="bg-emerald-600 hover:bg-emerald-500 text-white px-8 py-3.5 rounded-xl font-bold shadow-lg shadow-emerald-600/20 hover:shadow-emerald-600/40 transition transform active:scale-95 flex items-center">
                        <i data-lucide="save" class="w-5 h-5 mr-2"></i> Create User & Save Details
                    </button>
                </div>

            </form>
        </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); ?>;

        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 loadDivisionalSecretariats() {
            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);
                });
                dsSelect.disabled = false;
            }
        }

        function previewImage(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    var img = document.getElementById('preview');
                    var placeholder = document.getElementById('placeholder');
                    img.src = e.target.result;
                    img.classList.remove('hidden');
                    placeholder.classList.add('hidden');
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
    </script>
</body>
</html>
