<?php
session_start();
include_once 'connect.php';

// Fetch employee roles
$role_result = $conn->query("SELECT role_id, role_name FROM employee_roles");

$message = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Sanitize and validate inputs
    $full_name = isset($_POST['full_name']) ? trim($_POST['full_name']) : '';
    $emp_numb = isset($_POST['emp_numb']) ? trim($_POST['emp_numb']) : '';
    $cnic = isset($_POST['cnic']) ? trim($_POST['cnic']) : '';
    $repeat_cnic = isset($_POST['repeat_cnic']) ? trim($_POST['repeat_cnic']) : '';
    $dob = isset($_POST['dob']) ? $_POST['dob'] : '';
    $password = isset($_POST['password']) ? $_POST['password'] : '';
    $repeat_password = isset($_POST['repeat_password']) ? $_POST['repeat_password'] : '';
    $role_id = isset($_POST['role']) ? $_POST['role'] : '';

    // Capitalize each word in full name
    $full_name = ucwords(strtolower($full_name));

    // Remove hyphens from CNIC for validation, but store with hyphens in database
    $cnic_digits = str_replace('-', '', $cnic);
    $repeat_cnic_digits = str_replace('-', '', $repeat_cnic);
    
    // Convert DD-MM-YYYY to YYYY-MM-DD for database and age calculation
    $dob_mysql = '';
    if (!empty($dob) && preg_match('/^\d{2}-\d{2}-\d{4}$/', $dob)) {
        $date_parts = explode('-', $dob);
        $dob_mysql = $date_parts[2] . '-' . $date_parts[1] . '-' . $date_parts[0];
    }

    // Validate inputs
    if (empty($full_name)) {
        $message = "Please enter full name.";
    } elseif (empty($emp_numb)) {
        $message = "Please enter employee number.";
    } elseif (!preg_match('/^\d{8}$/', $emp_numb)) {
        $message = "Employee number must be exactly 8 digits.";
    } elseif (empty($cnic) || empty($repeat_cnic)) {
        $message = "Please enter CNIC in both fields.";
    } elseif ($cnic_digits !== $repeat_cnic_digits) {
        $message = "CNIC numbers do not match.";
    } elseif (!preg_match('/^\d{5}-\d{7}-\d{1}$/', $cnic)) {
        $message = "CNIC must be in format: XXXXX-XXXXXXX-X";
    } elseif (empty($dob)) {
        $message = "Please enter date of birth.";
    } elseif (!preg_match('/^\d{2}-\d{2}-\d{4}$/', $dob)) {
        $message = "Date of birth must be in DD-MM-YYYY format.";
    } else {
        // Age validation (minimum 18 years)
        $min_age = 18;
        if (!empty($dob_mysql)) {
            $user_age = date_diff(date_create($dob_mysql), date_create('today'))->y;
            if ($user_age < $min_age) {
                $message = "You must be at least $min_age years old to register.";
            }
        }
    }
    
    if (empty($message)) {
        if (empty($role_id)) {
            $message = "Please select a role.";
        } elseif (empty($password) || empty($repeat_password)) {
            $message = "Please enter password in both fields.";
        } elseif ($password !== $repeat_password) {
            $message = "Passwords do not match.";
        } elseif (strlen($password) < 8) {
            $message = "Password must be at least 8 characters long.";
        } elseif (!preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/', $password)) {
            $message = "Password must contain at least one uppercase letter, one lowercase letter, and one number.";
        } else {
			
            // Check if employee number already exists FIRST
            $check_emp_stmt = $conn->prepare("SELECT emp_numb FROM registrations_emp WHERE emp_numb = ?");
            $check_emp_stmt->bind_param("s", $emp_numb);
            $check_emp_stmt->execute();
            $check_emp_stmt->store_result();
        
            if ($check_emp_stmt->num_rows > 0) {
                $message = "This employee number has already been registered.";
                $check_emp_stmt->close();
            } else {
                $check_emp_stmt->close();
            
                // Then check if CNIC already exists (store with hyphens, so check with hyphens too)
                $check_stmt = $conn->prepare("SELECT cnic FROM registrations_emp WHERE cnic = ?");
                $check_stmt->bind_param("s", $cnic); // Now checking with hyphens
                $check_stmt->execute();
                $check_stmt->store_result();
            
                if ($check_stmt->num_rows > 0) {
                    $message = "This CNIC has already been registered.";
                    $check_stmt->close();
                } else {
                    $check_stmt->close();
                    
                    // Get role name
                    $stmt = $conn->prepare("SELECT role_name FROM employee_roles WHERE role_id = ?");
                    $stmt->bind_param("i", $role_id);
                    $stmt->execute();
                    $stmt->bind_result($role_name);
                    
                    if ($stmt->fetch()) {
                        $stmt->close();
                        
                        // All validations passed - register
                        $hashed_password = password_hash($password, PASSWORD_BCRYPT);
                        
                        try {
                            // Store CNIC WITH hyphens in database
                            $stmt = $conn->prepare("INSERT INTO registrations_emp (full_name, emp_numb, cnic, dob, role_id, password) VALUES (?, ?, ?, ?, ?, ?)");
                            $stmt->bind_param("ssssis", $full_name, $emp_numb, $cnic, $dob_mysql, $role_id, $hashed_password);
                            
                            if ($stmt->execute()) {
                                $message = "Registration submitted! Account activation requires administrator approval.";
                                // Clear form on successful submission
                                $_POST = array();
                            } else {
                                $message = "Error: " . $stmt->error;
                            }
                            $stmt->close();
                        } catch (Exception $e) {
                            $message = "Error: " . $e->getMessage();
                        }
                    } else {
                        $message = "Invalid role selected.";
                        $stmt->close();
                    }
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Employee Registration</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-LN+7fdVzj6u52u30Kp6M/trliBMCMKTyK833zpbD+pXdCLuTusPj697FH4R/5mcr" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/js/bootstrap.bundle.min.js" integrity="sha384-ndDqU0Gzau9qJ1lfW4pNLlhNTkCfHzAVBReH9diLvGRem5+R9g2FzA8ZGN954O5Q" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.11.3/css/lightbox.min.css">
    <link href="https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css" rel="stylesheet">
    <!-- Add jQuery UI for datepicker -->
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
    
    <style>
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    
    :root {
        --primary: #3498db;
        --primary-dark: #2980b9;
        --secondary: #2c3e50;
        --light: #ecf0f1;
        --dark: #34495e;
        --success: #2ecc71;
        --warning: #f39c12;
        --danger: #e74c3c;
        --gray: #95a5a6;
        --light-gray: #f5f7fa;
        --border-radius: 8px;
        --box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        --transition: all 0.3s ease;
    }
    
    body {
        background-color: #f5f7fa;
        min-height: 100vh;
    }
    
    .home-btn {
        position: fixed;
        top: 20px;
        left: 20px;
        background-color: #3498db;
        color: white;
        border: none;
        border-radius: 6px;
        padding: 10px 15px;
        font-size: 14px;
        cursor: pointer;
        transition: all 0.3s;
        display: flex;
        align-items: center;
        gap: 5px;
        z-index: 10;
    }
    
    .home-btn:hover {
        background-color: #2980b9;
    }
    
    .registration-container {
        background-color: white;
        border-radius: 10px;
        box-shadow: var(--box-shadow);
        overflow: hidden;
        height: 100%;
    }
    
    .registration-header {
        background: linear-gradient(135deg, var(--primary), var(--secondary));
        color: white;
        padding: 10px;
        text-align: center;
    }
    
    .registration-header h1 {
        font-size: 46px;
        font-weight: 600;
        margin-bottom: 1px;
    }
    
    .registration-body {
        padding: 20px;
    }
    
    .form-group {
        margin-bottom: 1.5rem;
        position: relative;
    }
    
    .form-control {
        width: 100%;
        padding: 12px 15px;
        border: 1px solid #ddd;
        border-radius: var(--border-radius);
        font-size: 16px;
        transition: var(--transition);
    }
    
    .form-control:focus {
        border-color: var(--primary);
        outline: none;
        box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
    }
    
    .input-group {
        position: relative;
        display: flex;
        align-items: center;
    }
    
    .input-group .form-control {
        flex: 1;
    }
    
    .toggle-password {
        position: absolute;
        right: 12px;
        cursor: pointer;
        color: var(--gray);
        font-size: 18px;
    }
    
    select.form-control {
        appearance: none;
        background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='%23333' viewBox='0 0 16 16'%3E%3Cpath d='M7.247 11.14 2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z'/%3E%3C/svg%3E");
        background-repeat: no-repeat;
        background-position: right 12px center;
        background-size: 16px;
    }
    
    .btn {
        display: inline-block;
        padding: 14px 20px;
        border: none;
        border-radius: var(--border-radius);
        font-size: 16px;
        font-weight: 500;
        cursor: pointer;
        transition: var(--transition);
        display: inline-flex;
        align-items: center;
        justify-content: center;
    }
    
    .btn-primary {
        background: var(--primary);
        color: white;
    }
    
    .btn-primary:hover {
        background: var(--primary-dark);
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(52, 152, 219, 0.3);
    }
    
    .btn-secondary {
        background: var(--light-gray);
        color: var(--secondary);
        border: 1px solid #ddd;
    }
    
    .btn-secondary:hover {
        background: #eaeef2;
    }
    
    .btn-danger {
        background: var(--light-gray);
        color: var(--danger);
        border: 1px solid #ddd;
    }
    
    .btn-danger:hover {
        background: #fdecea;
    }
    
    .btn-group {
        display: flex;
        justify-content: space-between;
        margin-top: 20px;
        gap: 10px;
    }
    
    ::placeholder {
        color: #6c757d;
        opacity: 1;
    }
    
    .image-container {
        position: relative;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
        padding: 40px;
        transition: all 0.3s ease;
    }
    
    .image-container img {
        max-width: 100%;
        max-height: 85vh;
        width: auto;
        object-fit: contain;
        border-radius: 12px;
        box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
        transition: all 0.4s ease;
    }
    
    .image-container:hover img {
        transform: scale(1.03);
    }
    
    .image-overlay {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(67, 97, 238, 0);
        border-radius: 12px;
        transition: all 0.3s ease;
    }
    
    .image-container:hover .image-overlay {
        background: rgba(67, 97, 238, 0.1);
    }
    
    .image-container:active {
        transform: scale(0.98);
    }
    
    /* Date field specific styling */
    .date-field {
        background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='%23333' viewBox='0 0 16 16'%3E%3Cpath d='M3.5 0a.5.5 0 0 1 .5.5V1h8V.5a.5.5 0 0 1 1 0V1h1a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3a2 2 0 0 1 2-2h1V.5a.5.5 0 0 1 .5-.5zM1 4v10a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V4H1z'/%3E%3C/svg%3E");
        background-repeat: no-repeat;
        background-position: right 12px center;
        background-size: 20px;
        padding-right: 40px;
    }
    
    /* Date input container with calendar icon */
    .date-input-container {
        position: relative;
    }
    
    .datepicker-trigger {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        cursor: pointer;
        color: var(--primary);
        font-size: 18px;
        z-index: 2;
    }
    
    /* Error message styling */
    .error-message {
        color: var(--danger);
        font-size: 0.85em;
        margin-top: 5px;
        display: none;
    }
    
    /* Login link styling - EXACTLY like the login page */
    .login-link {
        text-align: center;
        font-size: 15px;
        color: var(--secondary);
        margin-top: 20px;
        padding-top: 15px;
        border-top: 1px solid #eee;
    }
    
    .login-link a {
        color: var(--primary);
        text-decoration: none;
        font-weight: 500;
        transition: var(--transition);
    }
    
    .login-link a:hover {
        text-decoration: underline;
    }
    
    /* Watermark background */
    body::before {
        content: "";
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-image: url('images/dsis.png');
        background-repeat: no-repeat;
        background-position: center;
        background-size: 100%;
        opacity: 0.08;
        z-index: -1;
        pointer-events: none;
    }
    
    @media (max-width: 992px) {
        .image-container {
            display: none;
        }
        
        body::before {
            background-size: 100%;
            opacity: 0.05;
        }
        
        .btn-group {
            flex-direction: column;
        }
        
        .btn {
            width: 100%;
            margin-bottom: 10px;
        }
        
        .form-control {
            font-size: 16px; /* Prevent zoom on mobile */
        }
    }
</style>

</head>
<body>
    <div class="floating-decoration decoration-1"></div>
    <div class="floating-decoration decoration-2"></div>
    
    <button type="button" class="home-btn" onclick="window.location.href='index.php'">
        <i class="fas fa-arrow-left"></i> Back to Home
    </button>

    <div class="container-fluid h-100">
        <div class="row h-100 align-items-center">
        
            <!-- Left Column (Image) -->
            <div class="col-lg-6 d-flex justify-content-center align-items-center">
                <div class="image-container" onclick="window.location.href='register_emp.php'" style="cursor: pointer;">
                    <img src="images/dsis.png" alt="DSIS System" class="img-fluid" style="max-height: 85vh; width: auto;">
                    <div class="image-overlay"></div>
                </div>
            </div>
            
            <!-- Right Column (Registration Form) -->
            <div class="col-lg-6 py-4">
                <div class="registration-container mx-auto" style="max-width: 500px;">
                    <div class="registration-header">
                        <h1><strong style="text-decoration: underline;">Employee Registration</strong></h1>
                        <h4>AJ&K Education Department</h4>
                    </div>
                    
                    <div class="registration-body">
                        <form id="registration_form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" onsubmit="return validateForm()">
                        
                            <!-- Full Name -->
                          <div class="form-group">
                                <input type="text" id="full_name" name="full_name" class="form-control" 
                                       placeholder="Enter Full Name" required
                                       value="<?php echo isset($_POST['full_name']) ? htmlspecialchars($_POST['full_name']) : ''; ?>"
                                       onblur="capitalizeName(this)">
                            </div>
                            
                            <!-- EMPLOYEE NUMBER -->
                          <div class="form-group">
                                <input type="text" id="emp_numb" name="emp_numb" class="form-control" 
                                       placeholder="Enter 08 Digits Employee/Personal Number" required 
                                       maxlength="8" oninput="formatEmployeeNumber(this)"
                                       value="<?php echo isset($_POST['emp_numb']) ? htmlspecialchars($_POST['emp_numb']) : ''; ?>">
                            </div>

                            
                            <!-- CNIC -->
                          <div class="form-group">
                                <input 
                                    id="cnic" 
                                    name="cnic" 
                                    type="text"
                                    class="form-control"
                                    placeholder="Please enter CNIC in format: XXXXX-XXXXXXX-X"
                                    pattern="[0-9]{5}-[0-9]{7}-[0-9]{1}"
                                    maxlength="15"
                                    required
                                    oninput="formatCNIC(this)"
                                    value="<?php echo isset($_POST['cnic']) ? htmlspecialchars($_POST['cnic']) : ''; ?>">
                            </div>
                            
                            <!-- Repeat CNIC -->
                          <div class="form-group">
                                <input type="text" id="repeat_cnic" name="repeat_cnic" class="form-control" 
                                       placeholder="Repeat CNIC (XXXXX-XXXXXXX-X)" required 
                                       maxlength="15" oninput="formatRepeatCNIC(this)"
                                       value="<?php echo isset($_POST['repeat_cnic']) ? htmlspecialchars($_POST['repeat_cnic']) : ''; ?>">
                            </div>

                            <!-- Date of Birth -->
                            <div class="form-group" style="position: relative;">
                                <div class="date-input-container">
                                    <input id="dob" name="dob" type="text" class="form-control date-field"
                                           placeholder="Employee's Date of Birth in DD-MM-YYYY"
                                           maxlength="10"
                                           pattern="\d{2}-\d{2}-\d{4}"
                                           title="Please enter date in DD-MM-YYYY format"
                                           required
                                           value="<?php echo isset($_POST['dob']) ? htmlspecialchars($_POST['dob']) : ''; ?>">
                              </div>
                                <div id="dob-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                          </div>

                          <!-- Role Selection -->
                          <div class="form-group">
                                <select id="role" name="role" class="form-control" required>
                                    <option value="" selected disabled hidden>Select Employee Role</option>
                                    <?php 
                                    $role_result->data_seek(0);
                                    while ($row = $role_result->fetch_assoc()): ?>
                                        <option value="<?= $row['role_id'] ?>" 
                                            <?php echo (isset($_POST['role']) && $_POST['role'] == $row['role_id']) ? 'selected' : ''; ?>>
                                            <?= htmlspecialchars($row['role_name']) ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>

                            <!-- Password -->
                          <div class="form-group">
                                <div class="input-group">
                                    <input type="password" id="password" name="password" class="form-control" 
                                           placeholder="Enter Password (Minimum 8 characters)" required>
                                    <i class='bx bx-show toggle-password' onclick="togglePasswordVisibility('password')"></i>
                                </div>
                                <small class="text-muted">Must contain uppercase, lowercase letters and a number</small>
                            </div>

                            <!-- Confirm Password -->
                          <div class="form-group">
                                <div class="input-group">
                                    <input type="password" id="repeat_password" name="repeat_password" 
                                           class="form-control" placeholder="Confirm Password" required>
                                    <i class='bx bx-show toggle-password' onclick="togglePasswordVisibility('repeat_password')"></i>
                                </div>
                            </div>

                            <!-- Form Buttons -->
                            <div class="btn-group row g-2">
                                <div class="col">
                                    <button type="submit" class="btn btn-primary w-100 py-2">
                                        <i class="fas fa-user-plus me-1"></i> Register
                                    </button>
                                </div>
                                <div class="col">
                                    <button type="button" class="btn btn-secondary w-100 py-2" onclick="resetForm()">
                                        <i class="fas fa-redo me-1"></i> Reset
                                    </button>
                                </div>
                                <div class="col">
                                    <button type="button" class="btn btn-danger w-100 py-2" onclick="cancelRegistration()">
                                        <i class="fas fa-times me-1"></i> Cancel
                                    </button>
                                </div>
                            </div>
                            
                            <!-- Login Link - EXACTLY like the login page -->
                            <div class="login-link">
                                Already have an Account? <a href="login_emp.php">Login From Here</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

<!-- Add jQuery and jQuery UI -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

<script>
    function formatCNIC(input) {
        // Get cursor position before formatting
        const cursorPosition = input.selectionStart;
        
        // Remove all non-digit characters
        let value = input.value.replace(/\D/g, '');
        
        // Apply formatting: XXXXX-XXXXXXX-X
        if (value.length > 5) {
            value = value.substring(0, 5) + '-' + value.substring(5);
        }
        if (value.length > 13) {
            value = value.substring(0, 13) + '-' + value.substring(13);
        }
        
        // Ensure maximum length of 15 characters (including hyphens)
        if (value.length > 15) {
            value = value.substring(0, 15);
        }
        
        // Update the input value
        input.value = value;
        
        // Adjust cursor position after formatting
        // If cursor was before a hyphen that was added, move it forward
        let newCursorPosition = cursorPosition;
        if (cursorPosition === 6 && value.length >= 6 && value.charAt(5) === '-') {
            newCursorPosition = 7;
        } else if (cursorPosition === 14 && value.length >= 14 && value.charAt(13) === '-') {
            newCursorPosition = 15;
        }
        
        // Set the cursor position
        input.setSelectionRange(newCursorPosition, newCursorPosition);
    }

    function formatRepeatCNIC(input) {
        // Get cursor position before formatting
        const cursorPosition = input.selectionStart;
        
        // Remove all non-digit characters
        let value = input.value.replace(/\D/g, '');
        
        // Apply formatting: XXXXX-XXXXXXX-X
        if (value.length > 5) {
            value = value.substring(0, 5) + '-' + value.substring(5);
        }
        if (value.length > 13) {
            value = value.substring(0, 13) + '-' + value.substring(13);
        }
        
        // Ensure maximum length of 15 characters (including hyphens)
        if (value.length > 15) {
            value = value.substring(0, 15);
        }
        
        // Update the input value
        input.value = value;
        
        // Adjust cursor position after formatting
        // If cursor was before a hyphen that was added, move it forward
        let newCursorPosition = cursorPosition;
        if (cursorPosition === 6 && value.length >= 6 && value.charAt(5) === '-') {
            newCursorPosition = 7;
        } else if (cursorPosition === 14 && value.length >= 14 && value.charAt(13) === '-') {
            newCursorPosition = 15;
        }
        
        // Set the cursor position
        input.setSelectionRange(newCursorPosition, newCursorPosition);
    }

    function formatEmployeeNumber(input) {
        // Remove all non-digit characters
        let value = input.value.replace(/\D/g, '');
        
        // Ensure maximum length of 8 digits
        if (value.length > 8) {
            value = value.substring(0, 8);
        }
        
        // Update the input value
        input.value = value;
    }

    function resetForm() {
        document.getElementById('registration_form').reset();
        // Destroy and reinitialize datepicker
        $('#dob').datepicker('destroy');
        initializeDatePicker();
    }

    function cancelRegistration() {
        if (confirm('Are you sure you want to cancel registration?')) {
            window.location.href = 'index.php';
        }
    }

    function togglePasswordVisibility(fieldId) {
        const passwordField = document.getElementById(fieldId);
        const icon = passwordField.nextElementSibling;
        
        if (passwordField.type === 'password') {
            passwordField.type = 'text';
            icon.classList.replace('bx-show', 'bx-hide');
        } else {
            passwordField.type = 'password';
            icon.classList.replace('bx-hide', 'bx-show');
        }
    }
    
    // New function to capitalize each word
    function capitalizeName(input) {
        let value = input.value.trim();
        if (value) {
            // Convert to lowercase first, then capitalize each word
            value = value.toLowerCase().replace(/\b\w/g, function(char) {
                return char.toUpperCase();
            });
            input.value = value;
        }
    }

    // Date validation functions
    function parseDDMMYYYY(dateStr) {
        if (!dateStr || typeof dateStr !== 'string') return null;
        
        const parts = dateStr.split('-');
        if (parts.length !== 3) return null;
        
        const day = parseInt(parts[0], 10);
        const month = parseInt(parts[1], 10) - 1; // Months are 0-indexed in JS
        const year = parseInt(parts[2], 10);
        
        if (isNaN(day) || isNaN(month) || isNaN(year)) return null;
        
        // Create date object (note: month is 0-indexed)
        const date = new Date(year, month, day);
        
        // Check if the date is valid
        if (date.getDate() !== day || date.getMonth() !== month || date.getFullYear() !== year) {
            return null;
        }
        
        return date;
    }

    function validateDateFormat(inputId) {
        const input = document.getElementById(inputId);
        const errorElement = document.getElementById(inputId + '-error');
        const value = input.value.trim();
        
        if (!value) {
            if (errorElement) errorElement.style.display = 'none';
            input.setCustomValidity('');
            return true;
        }
        
        const datePattern = /^(\d{2})-(\d{2})-(\d{4})$/;
        if (!datePattern.test(value)) {
            if (errorElement) {
                errorElement.textContent = "Invalid date format (DD-MM-YYYY)";
                errorElement.style.display = 'block';
            }
            input.style.borderColor = 'var(--danger)';
            input.style.boxShadow = '0 0 0 2px rgba(231, 76, 60, 0.2)';
            input.setCustomValidity('Please enter date in DD-MM-YYYY format');
            return false;
        }
        
        const parts = value.split('-');
        const day = parseInt(parts[0], 10);
        const month = parseInt(parts[1], 10) - 1;
        const year = parseInt(parts[2], 10);
        
        const inputDate = new Date(year, month, day);
        if (isNaN(inputDate.getTime()) || 
            inputDate.getDate() !== day || 
            inputDate.getMonth() !== month || 
            inputDate.getFullYear() !== year) {
            if (errorElement) {
                errorElement.textContent = "Invalid date!";
                errorElement.style.display = 'block';
            }
            input.style.borderColor = 'var(--danger)';
            input.style.boxShadow = '0 0 0 2px rgba(231, 76, 60, 0.2)';
            input.setCustomValidity('Invalid date');
            return false;
        }
        
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        
        if (inputDate > today) {
            if (errorElement) {
                errorElement.textContent = "Date cannot be in the future!";
                errorElement.style.display = 'block';
            }
            input.style.borderColor = 'var(--danger)';
            input.style.boxShadow = '0 0 0 2px rgba(231, 76, 60, 0.2)';
            input.setCustomValidity('Date cannot be in the future');
            return false;
        }
        
        // Age validation (minimum 18 years)
        if (inputId === 'dob') {
            let age = today.getFullYear() - inputDate.getFullYear();
            const monthDiff = today.getMonth() - inputDate.getMonth();
            
            if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < inputDate.getDate())) {
                age--;
            }
            
            if (age < 18) {
                if (errorElement) {
                    errorElement.textContent = "You must be at least 18 years old to register";
                    errorElement.style.display = 'block';
                }
                input.style.borderColor = 'var(--danger)';
                input.style.boxShadow = '0 0 0 2px rgba(231, 76, 60, 0.2)';
                input.setCustomValidity('You must be at least 18 years old to register');
                return false;
            }
        }
        
        if (errorElement) errorElement.style.display = 'none';
        input.style.borderColor = '';
        input.style.boxShadow = '';
        input.setCustomValidity('');
        return true;
    }

    function validateForm() {
        // Capitalize name before submission
        const nameInput = document.getElementById('full_name');
        capitalizeName(nameInput);
        
        const fullName = document.getElementById('full_name').value;
        const emp_numb = document.getElementById('emp_numb').value;
        const cnic = document.getElementById('cnic').value;
        const repeatCnic = document.getElementById('repeat_cnic').value;
        const dob = document.getElementById('dob').value;
        const role = document.getElementById('role').value;
        const password = document.getElementById('password').value;
        const repeatPassword = document.getElementById('repeat_password').value;
        
        if (!fullName) {
            alert('Please enter full name');
            return false;
        }
        
        if (emp_numb.length !== 8 || !/^\d+$/.test(emp_numb)) {
            alert('Employee number must be exactly 8 digits');
            return false;
        }
        
        // Check CNIC format with hyphens
        const cnicPattern = /^\d{5}-\d{7}-\d{1}$/;
        if (!cnicPattern.test(cnic)) {
            alert('CNIC must be in format: XXXXX-XXXXXXX-X');
            return false;
        }
        
        // Remove hyphens for comparison
        const cnicDigits = cnic.replace(/\D/g, '');
        const repeatCnicDigits = repeatCnic.replace(/\D/g, '');
        
        if (cnicDigits !== repeatCnicDigits) {
            alert('CNIC numbers do not match');
            return false;
        }
        
        if (!dob) {
            alert('Please enter date of birth');
            return false;
        }
        
        // Validate date format
        if (!validateDateFormat('dob')) {
            alert('Please check the date of birth');
            return false;
        }
        
        if (!role) {
            alert('Please select employee role');
            return false;
        }
        
        if (password.length < 8) {
            alert('Password must be at least 8 characters long');
            return false;
        }
        
        // Password strength validation
        const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
        if (!passwordRegex.test(password)) {
            alert('Password must contain at least one uppercase letter, one lowercase letter, and one number');
            return false;
        }
        
        if (password !== repeatPassword) {
            alert('Passwords do not match');
            return false;
        }
        
        return true;
    }

    // Initialize datepicker
    function initializeDatePicker() {
        $('#dob').datepicker({
            dateFormat: 'dd-mm-yy',
            changeMonth: true,
            changeYear: true,
            yearRange: '-100:+0',
            maxDate: 0, // No future dates
            showOtherMonths: true,
            selectOtherMonths: true,
            beforeShowDay: function(date) {
                var today = new Date();
                today.setHours(0, 0, 0, 0);
                return [date <= today, ""];
            },
            onSelect: function(dateText, inst) {
                const errorElement = document.getElementById('dob-error');
                if (errorElement) errorElement.style.display = 'none';
                validateDateFormat('dob');
            },
            onClose: function(dateText, inst) {
                validateDateFormat('dob');
            }
        }).on('keydown', function(e) {
            if (e.keyCode === 13) {
                $(this).datepicker('hide');
                validateDateFormat('dob');
                e.preventDefault();
                return false;
            }
        }).on('blur', function() {
            validateDateFormat('dob');
        });
    }

    // Function to show date picker
    function showDatePicker(fieldId) {
        $('#' + fieldId).datepicker('show');
    }

    // Prevent user from typing non-numeric characters in CNIC and Date fields
    document.addEventListener('DOMContentLoaded', function() {
        const cnicInput = document.getElementById('cnic');
        const repeatCnicInput = document.getElementById('repeat_cnic');
        const dobInput = document.getElementById('dob');
        
        cnicInput.addEventListener('keydown', function(e) {
            // Allow: backspace, delete, tab, escape, enter, arrows
            if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
                // Allow: Ctrl+A, Ctrl+C, Ctrl+V, Ctrl+X
                (e.keyCode === 65 && e.ctrlKey === true) ||
                (e.keyCode === 67 && e.ctrlKey === true) ||
                (e.keyCode === 86 && e.ctrlKey === true) ||
                (e.keyCode === 88 && e.ctrlKey === true) ||
                // Allow: home, end, left, right
                (e.keyCode >= 35 && e.keyCode <= 39)) {
                return;
            }
            
            // Ensure that it is a number
            if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                e.preventDefault();
            }
        });
        
        repeatCnicInput.addEventListener('keydown', function(e) {
            // Allow: backspace, delete, tab, escape, enter, arrows
            if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
                // Allow: Ctrl+A, Ctrl+C, Ctrl+V, Ctrl+X
                (e.keyCode === 65 && e.ctrlKey === true) ||
                (e.keyCode === 67 && e.ctrlKey === true) ||
                (e.keyCode === 86 && e.ctrlKey === true) ||
                (e.keyCode === 88 && e.ctrlKey === true) ||
                // Allow: home, end, left, right
                (e.keyCode >= 35 && e.keyCode <= 39)) {
                return;
            }
            
            // Ensure that it is a number
            if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                e.preventDefault();
            }
        });
        
        dobInput.addEventListener('keydown', function(e) {
            // Allow: backspace, delete, tab, escape, enter, arrows, hyphen (189, 109, 173)
            if ([46, 8, 9, 27, 13, 110, 189, 109, 173].indexOf(e.keyCode) !== -1 ||
                // Allow: Ctrl+A, Ctrl+C, Ctrl+V, Ctrl+X
                (e.keyCode === 65 && e.ctrlKey === true) ||
                (e.keyCode === 67 && e.ctrlKey === true) ||
                (e.keyCode === 86 && e.ctrlKey === true) ||
                (e.keyCode === 88 && e.ctrlKey === true) ||
                // Allow: home, end, left, right
                (e.keyCode >= 35 && e.keyCode <= 39)) {
                return;
            }
            
            // Ensure that it is a number
            if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                e.preventDefault();
            }
        });

        // Initialize date picker
        initializeDatePicker();

        // Validate date on page load if it exists
        if (dobInput.value) {
            validateDateFormat('dob');
        }
    });

    // Show alert message if exists
    window.onload = function() {
        <?php if (!empty($message)): ?>
            alert('<?php echo addslashes($message); ?>');
        <?php endif; ?>
    };
</script>

</body>
</html>
<?php
// Close database connection at the very end
$conn->close();
?>