<?php
include '../db_config.php';
include '../functions.php';
$msg = '';
$error = '';
$show_login = isset($_GET['mode']) && $_GET['mode'] == 'login';
$nic_val = '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // LOGIN LOGIC (If user tries to login from here)
    if (isset($_POST['login_action'])) {
        $u = sanitize_input($_POST['nic']);
        $p = $_POST['password'];
        $stmt = $conn->prepare("SELECT nic, password, role FROM employee_login WHERE nic=?");
        $stmt->bind_param("s", $u);
        $stmt->execute();
        $stmt->bind_result($fetched_nic, $hash, $role);

        if ($stmt->fetch() && password_verify($p, $hash)) {
            session_start();
            $_SESSION['user_id'] = $fetched_nic; // Store NIC as user_id
            $_SESSION['username'] = $fetched_nic;
            $_SESSION['role'] = $role;
            header("Location: dashboard.php");
            exit();
        } else {
            $error = "Invalid credential. Please try again.";
            $show_login = true; // Stay on login mode
            $nic_val = $u;
        }
    }
    // REGISTER LOGIC
    else {
        // Required Fields
        $nic = sanitize_input($_POST['nic']);
        $pass = $_POST['password'];
        $cpass = $_POST['confirm_password'];

        $full_name = sanitize_input($_POST['full_name']);
        $dob = sanitize_input($_POST['dob']);
        $phone = sanitize_input($_POST['phone']);
        $address = sanitize_input($_POST['address']);
        $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']);
        }
        $job_category = sanitize_input($_POST['job_category']);
        if ($job_category == 'Other') {
            $job_category = sanitize_input($_POST['job_category_other']);
        }

        $nic_val = $nic;

        if (!isset($_POST['terms_agreed'])) {
            $error = "You must agree to the terms and conditions to register.";
        } elseif ($pass !== $cpass) {
            $error = "Passwords do not match.";
        } else {
            $password_hash = password_hash($pass, PASSWORD_DEFAULT);

            // Check if NIC already exists
            $check = $conn->query("SELECT nic FROM employee_login WHERE nic = '$nic'");
            if ($check->num_rows > 0) {
                $error = "This NIC is already registered. Please login below.";
                $show_login = true;
            } else {

                // 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.";
                    }
                }


                if (!$error) {
                    $conn->begin_transaction();
                    try {
                        // 1. Insert Login
                        $stmt1 = $conn->prepare("INSERT INTO employee_login (nic, password, role) VALUES (?, ?, 'employee')");
                        $stmt1->bind_param("ss", $nic, $password_hash);
                        $stmt1->execute();

                        // 2. Insert Details
                        $stmt2 = $conn->prepare("INSERT INTO employee_details (employee_nic, nic, status, full_name, dob, qualification, job_category, phone, address, district, divisional_secretariat, experience, profile_pic, cv_file) VALUES (?, ?, 'Pending', ?, ?, ?, ?, ?, ?, ?, ?, '', ?, '')");
                        $stmt2->bind_param("sssssssssss", $nic, $nic, $full_name, $dob, $qualification, $job_category, $phone, $address, $district, $div_sec, $profile_pic_name);
                        $stmt2->execute();

                        $conn->commit();
                        $msg = "Registration successful! You have been added to the approval queue. Please login to complete your profile.";
                        $show_login = true;

                    } catch (Exception $e) {
                        $conn->rollback();
                        $error = "Registration failed: " . $e->getMessage();
                    }
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Worker Registration | 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.7);
            backdrop-filter: blur(12px);
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .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 flex items-center justify-center p-4 selection:bg-indigo-500 selection:text-white">

    <div class="max-w-4xl w-full flex flex-col md:flex-row shadow-2xl rounded-3xl overflow-hidden glass-panel">

        <!-- Left Side: Branding/Info -->
        <div
            class="md:w-5/12 bg-indigo-900/50 p-12 text-white flex flex-col justify-center relative overflow-hidden border-r border-slate-700/50">
            <!-- Background effects -->
            <div class="absolute top-0 left-0 w-full h-full bg-gradient-to-br from-indigo-600/20 to-slate-900/90 z-0">
            </div>
            <div class="absolute -top-12 -right-12 w-48 h-48 bg-indigo-500 rounded-full blur-[60px] opacity-40 z-0">
            </div>
            <div class="absolute bottom-12 -left-12 w-48 h-48 bg-emerald-500 rounded-full blur-[60px] opacity-20 z-0">
            </div>

            <div class="relative z-10">
                <a href="<?= BASE_URL ?>/index.php" class="inline-block group mb-8">
                    <h1
                        class="text-3xl font-bold italic tracking-tighter group-hover:opacity-80 transition-all brand-pop block origin-left">
                        Work For <span class="text-indigo-400">Sri Lanka</span></h1>
                </a>

                <h2 class="text-3xl font-semibold mb-4 text-white">Find Your <br /><span class="text-indigo-300">Next
                        Opportunity</span></h2>
                <p class="text-slate-300 text-lg mb-8 leading-relaxed">Register your skills and let employers find you.
                    Join thousands of Sri Lankans finding work every day.</p>

                <div class="space-y-4">
                    <div class="flex items-center space-x-4 p-4 rounded-xl bg-slate-800/50 border border-slate-700">
                        <div class="bg-indigo-500/20 p-2.5 rounded-lg text-indigo-400">
                            <i data-lucide="briefcase" class="w-6 h-6"></i>
                        </div>
                        <span class="text-slate-200 font-medium">Browse 1,000+ Active Jobs</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Right Side: Form -->
        <div class="md:w-7/12 p-8 md:p-12 max-h-[90vh] overflow-y-auto bg-slate-900/40 custom-scrollbar">
            <div class="mb-8">
                <?php if ($show_login): ?>
                    <h3 class="text-3xl font-bold text-white">Welcome Back</h3>
                    <p class="text-slate-400 mt-2">Login to manage your profile.</p>
                <?php else: ?>
                    <h3 class="text-3xl font-bold text-white">Worker Signup</h3>
                    <p class="text-slate-400 mt-2">Create your professional profile today.</p>
                <?php endif; ?>
            </div>

            <?php if ($msg): ?>
                <div
                    class="bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 p-4 rounded-xl mb-6 text-sm flex items-center">
                    <i data-lucide="check-circle" class="w-5 h-5 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 p-4 rounded-xl mb-6 text-sm flex items-center">
                    <i data-lucide="alert-circle" class="w-5 h-5 mr-3 flex-shrink-0"></i>
                    <?= $error ?>
                </div>
            <?php endif; ?>

            <?php if ($show_login): ?>
                <!-- LOGIN FORM -->
                <form method="post" class="space-y-6">
                    <input type="hidden" name="login_action" value="1">
                    <div>
                        <label class="block text-sm font-semibold text-slate-300 mb-2">NIC Number</label>
                        <input type="text" name="nic" required value="<?= $nic_val ?>"
                            class="w-full px-4 py-4 rounded-xl form-input outline-none">
                    </div>
                    <div>
                        <label class="block text-sm font-semibold text-slate-300 mb-2">Password</label>
                        <input type="password" name="password" required
                            class="w-full px-4 py-4 rounded-xl form-input outline-none">
                    </div>
                    <button type="submit"
                        class="w-full bg-indigo-600 hover:bg-indigo-500 text-white font-bold py-4 rounded-xl shadow-lg shadow-indigo-600/20 transition transform active:scale-[0.98]">
                        Sign In Now
                    </button>
                    <div class="mt-4 text-center space-y-2">
                        <a href="register.php" class="block text-slate-400 text-sm hover:text-white transition">Don't have
                            an account? <span class="text-indigo-400 font-bold">Register</span></a>
                        <a href="change_password.php"
                            class="block text-slate-500 text-xs hover:text-slate-300 transition">Forgot Password?</a>
                    </div>
                </form>
            <?php else: ?>
                <!-- REGISTER FORM -->
                <form method="post" enctype="multipart/form-data" class="space-y-6">

                    <!-- NIC & Password Section -->
                    <div class="space-y-5 bg-slate-800/30 p-6 rounded-2xl border border-slate-700/50">
                        <h4 class="text-xs font-bold text-indigo-400 uppercase tracking-widest mb-2">Account Setup</h4>
                        <div>
                            <label class="block text-sm font-semibold text-slate-300 mb-1">NIC Number <span
                                    class="text-red-400">*</span></label>
                            <input type="text" name="nic" required value="<?= $nic_val ?>"
                                class="w-full px-4 py-3 rounded-xl form-input outline-none" placeholder="Ex: 200012345678">
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                            <div>
                                <label class="block text-sm font-semibold text-slate-300 mb-1">Password <span
                                        class="text-red-400">*</span></label>
                                <input type="password" name="password" required
                                    class="w-full px-4 py-3 rounded-xl form-input outline-none" placeholder="Min 6 chars">
                            </div>
                            <div>
                                <label class="block text-sm font-semibold text-slate-300 mb-1">Confirm Password <span
                                        class="text-red-400">*</span></label>
                                <input type="password" name="confirm_password" required
                                    class="w-full px-4 py-3 rounded-xl form-input outline-none"
                                    placeholder="Re-enter password">
                            </div>
                        </div>
                    </div>

                    <!-- Personal Details -->
                    <div class="space-y-5">
                        <h4 class="text-xs font-bold text-indigo-400 uppercase tracking-widest mb-2 mt-4">Personal Details
                        </h4>

                        <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">
                            <img id="preview" src=""
                                class="hidden w-24 h-24 rounded-full object-cover border-4 border-slate-700 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 <input type="file" name="profile_pic" accept="image/*" class="hidden"
                                    onchange="previewImage(this)">
                            </label>
                        </div>

                        <div>
                            <label class="block text-sm font-semibold text-slate-300 mb-1">Full Name <span
                                    class="text-red-400">*</span></label>
                            <input type="text" name="full_name" required
                                class="w-full px-4 py-3 rounded-xl form-input outline-none" placeholder="Your full name">
                        </div>

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                            <div>
                                <label class="block text-sm font-semibold text-slate-300 mb-1">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-1">Phone Number <span
                                        class="text-red-400">*</span></label>
                                <input type="text" name="phone" required
                                    class="w-full px-4 py-3 rounded-xl form-input outline-none" placeholder="07XXXXXXXX">
                            </div>
                        </div>

                        <div>
                            <label class="block text-sm font-semibold text-slate-300 mb-1">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"
                                placeholder="Permanent address"></textarea>
                        </div>

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                            <div>
                                <label class="block text-sm font-semibold text-slate-300 mb-1">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-1">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 class="grid grid-cols-1 md:grid-cols-2 gap-5">
                            <div>
                                <label class="block text-sm font-semibold text-slate-300 mb-1">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 Highest Qual.</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="Degree" class="bg-slate-900">Degree</option>
                                    <option value="Other" class="bg-slate-900">Other</option>
                                </select>
                                <div id="nvq_level_div" style="display:none;" class="mt-2">
                                    <label class="block text-sm font-semibold text-slate-400 mb-1 mt-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-1">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="Specify category"
                                    class="mt-2 w-full px-4 py-2 bg-slate-800 border border-slate-600 rounded-xl text-sm focus:border-indigo-500 transition outline-none text-white"
                                    style="display:none;">
                            </div>
                        </div>

                    </div>

                    <div class="flex items-start space-x-3 mb-4">
                        <div class="flex items-center h-5">
                            <input id="terms_agreed" name="terms_agreed" type="checkbox" required
                                class="w-5 h-5 rounded border-slate-700 bg-slate-800 text-indigo-600 focus:ring-indigo-600/20 cursor-pointer">
                        </div>
                        <div class="text-sm">
                            <label for="terms_agreed" class="font-medium text-slate-300 cursor-pointer">
                                I agreed to terms and conditions of wadakarayo.lk <span class="text-red-400">*</span>
                            </label>
                        </div>
                    </div>


                    <button type="submit"
                        class="w-full bg-emerald-600 hover:bg-emerald-500 text-white font-bold py-4 rounded-xl shadow-lg shadow-emerald-600/20 transition transform active:scale-[0.98] mt-6">
                        Complete Registration
                    </button>
                    <div class="mt-4 text-center">
                        <p class="text-slate-400 text-sm">Already a member? <a href="register.php?mode=login"
                                class="text-indigo-400 font-bold hover:text-white transition">Sign In</a></p>
                    </div>
                </form>
            <?php endif; ?>

            <div class="mt-8 text-center border-t border-slate-800 pt-6">
                <a href="<?= BASE_URL ?>/index.php"
                    class="text-slate-500 text-xs hover:text-slate-300 transition flex items-center justify-center gap-1">
                    <i data-lucide="home" class="w-3 h-3"></i> Back to Home
                </a>
            </div>
        </div>
    </div>

    <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>