Server : LiteSpeed
System : Linux terra.hostitbro.com 5.14.0-611.54.3.el9_7.x86_64 #1 SMP PREEMPT_DYNAMIC Thu May 7 16:31:24 EDT 2026 x86_64
User : outerorb ( 1091)
PHP Version : 8.1.34
Disable Function : mail
Directory :  /home2/outerorb/emp.outerorbittech.in/admin/

📁 Create New:
⬆️ Upload File:
Current Dir [ Writable ] Root [ Writable ]


OR Upload from URL:
URL: Save as:

📄 File: edit.php

Path: /home2/outerorb/emp.outerorbittech.in/admin/edit.php

Size: 55.94 KB

Permissions: 0666

<?php
require __DIR__ . '/../includes/helpers.php';
require_admin();
ensure_employees_table();
ensure_designations_table();
ensure_employee_auth_table();

$admin = current_admin();
$roleLabel = (($admin['role'] ?? '') === 'super') ? 'Super Admin' : 'Admin';
$id = isset($_GET['id']) ? (int) $_GET['id'] : (isset($_POST['id']) ? (int) $_POST['id'] : 0);
if (!$id) {
    redirect_with_message('dashboard.php', 'Invalid record.', 'error');
}

$pdo = db();
$stmt = $pdo->prepare('SELECT * FROM employees WHERE id = ? LIMIT 1');
$stmt->execute([$id]);
$emp = $stmt->fetch();
$aadhaarPaths = parse_aadhaar_paths($emp['aadhaar_path'] ?? '');

if (!$emp) {
    redirect_with_message('dashboard.php', 'Record not found.', 'error');
}

enforce_department_access($emp);

if (!empty($emp['deleted_at'])) {
    redirect_with_message('trash.php', 'Record is in Trash. Restore it before editing.', 'error');
}

$flash = flash();
$errors = $flash['errors'] ?? [];
$old = $flash['old'] ?? [];

// Merge existing DB values with any flashed old input so user does not lose progress
$form = array_merge($emp, $old);
$form['mother_name'] = $form['mother_name'] ?? '';
$form['emergency_contact_name'] = $form['emergency_contact_name'] ?? '';
$form['emergency_contact_number'] = $form['emergency_contact_number'] ?? ($form['emergency_contact'] ?? '');
$form['emergency_contact_relation'] = $form['emergency_contact_relation'] ?? '';
$form['employee_status'] = $form['employee_status'] ?? 'Active';
$departments = is_super_admin() ? list_departments() : allowed_departments_for_admin();
$designationActive = list_designations(true);
$currentDesignationId = isset($form['designation_id']) ? (int) $form['designation_id'] : null;
$designationOptions = [];
foreach ($designationActive as $row) {
    $designationOptions[(int) $row['id']] = $row;
}
if ($currentDesignationId) {
    $existingDesignation = get_designation_by_id($currentDesignationId);
    if ($existingDesignation) {
        $designationOptions[(int) $existingDesignation['id']] = $existingDesignation;
    }
}
$designationOptions = array_values($designationOptions);
usort($designationOptions, fn($a, $b) => strcasecmp($a['name'], $b['name']));
$designationActiveIds = array_map(fn($row) => (int) $row['id'], $designationActive);
$statusOptions = ['Active', 'Left', 'Terminated', 'Absconded / Defaulted'];
$emergencyRelations = ['Father', 'Mother', 'Brother', 'Sister', 'Spouse', 'Relative', 'Friend', 'Other'];
$maritalStatusOptions = ['Single', 'Married', 'Divorced', 'Widowed', 'Separated'];
$genderOptions = ['Male', 'Female', 'Other', 'Prefer not to say'];
$bloodGroupOptions = ['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-'];
$qualificationOptions = ['10th Pass', '12th Pass', 'Diploma', "Bachelor's Degree", "Master's Degree", 'PhD', 'Other'];

$appendCurrentOption = function (array $options, ?string $current): array {
    $current = trim((string) $current);
    if ($current !== '' && !in_array($current, $options, true)) {
        $options[] = $current; // keep legacy value selectable
    }
    return $options;
};

$maritalStatusChoices = $appendCurrentOption($maritalStatusOptions, $form['marital_status'] ?? '');
$genderChoices = $appendCurrentOption($genderOptions, $form['gender'] ?? '');
$bloodGroupChoices = $appendCurrentOption($bloodGroupOptions, $form['blood_group'] ?? '');
$qualificationChoices = $appendCurrentOption($qualificationOptions, $form['highest_qualification'] ?? '');

$requiredFields = [
    'first_name' => 'Full name',
    'last_name' => "Father's name",
    'mother_name' => "Mother's name",
    'email' => 'Email',
    'phone' => 'Contact number',
    'emergency_contact_name' => 'Emergency contact name',
    'emergency_contact_number' => 'Emergency contact number',
    'emergency_contact_relation' => 'Emergency contact relation',
    'dob' => 'Date of birth',
    'date_of_joining' => 'Date of joining',
    'address' => 'Present address',
    'permanent_address' => 'Permanent address',
    'zip' => 'Present ZIP / PIN',
    'aadhaar_number' => 'Aadhaar number',
    'pan_number' => 'PAN number',
    'highest_qualification' => 'Highest qualification',
    'department' => 'Department / Process',
    'designation_id' => 'Designation',
    'employee_status' => 'Employee status',
    'marital_status' => 'Marital status',
    'gender' => 'Gender',
    'identity_mark' => 'Identity mark',
    'blood_group' => 'Blood group',
    'referred_by' => 'Referred by',
    'account_number' => 'Account number',
    'ifsc_code' => 'IFSC code',
    'bank_name' => 'Bank name',
];

$docColumns = [
    'pan' => 'pan_path',
    'qualification' => 'qualification_path',
    'tenth_marksheet' => 'tenth_marksheet_path',
    'twelfth_marksheet' => 'twelfth_marksheet_path',
    'bank_proof' => 'bank_proof_path',
    'photo' => 'photo_path',
];

$docLabels = [
    'pan' => 'PAN Document',
    'qualification' => 'Graduation',
    'tenth_marksheet' => '10th Marksheet',
    'twelfth_marksheet' => '12th Marksheet',
    'bank_proof' => 'Bank Proof',
    'photo' => 'Passport Photo',
];

$pendingDocs = [];
$aadhaarFrontPath = $aadhaarPaths['front'] ?? null;
$aadhaarBackPath = $aadhaarPaths['back'] ?? null;
$aadhaarFrontHasFile = (bool) resolve_upload_path($aadhaarFrontPath);
$aadhaarBackHasFile = (bool) resolve_upload_path($aadhaarBackPath);
if (!$aadhaarFrontHasFile) {
    $pendingDocs[] = 'Aadhaar Front';
}
if (!$aadhaarBackHasFile) {
    $pendingDocs[] = 'Aadhaar Back';
}

foreach ($docColumns as $field => $col) {
    if ($field === 'qualification') {
        continue;
    }
    if (!resolve_upload_path($emp[$col] ?? null)) {
        $pendingDocs[] = $docLabels[$field] ?? $field;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !verify_csrf($_POST['csrf_token'])) {
        redirect_with_message('edit.php?id=' . $id, 'Session expired. Please try again.', 'error');
    }

    // Handle employee access deactivation
    if (!empty($_POST['action']) && $_POST['action'] === 'deactivate') {
        ensure_employee_auth_table();
        $pdo->beginTransaction();
        try {
            // Update employee status
            $stmt = $pdo->prepare('UPDATE employees SET employee_status = ? WHERE id = ?');
            $stmt->execute(['Left', $id]);
            
            // Disable auth access
            $stmt = $pdo->prepare('UPDATE employee_auth SET is_active = 0 WHERE employee_id = ?');
            $stmt->execute([$id]);
            
            $pdo->commit();
            log_login_attempt($emp['phone'], 'account_disabled', $id);
            redirect_with_message('edit.php?id=' . $id, 'Employee access has been deactivated. Data retained for records.', 'success');
        } catch (Exception $e) {
            $pdo->rollBack();
            redirect_with_message('edit.php?id=' . $id, 'Failed to deactivate employee access.', 'error');
        }
    }

    // Handle employee access reactivation
    if (!empty($_POST['action']) && $_POST['action'] === 'reactivate') {
        ensure_employee_auth_table();
        $pdo->beginTransaction();
        try {
            // Update employee status to Active
            $stmt = $pdo->prepare('UPDATE employees SET employee_status = ? WHERE id = ?');
            $stmt->execute(['Active', $id]);
            
            // Re-enable auth access
            $stmt = $pdo->prepare('UPDATE employee_auth SET is_active = 1 WHERE employee_id = ?');
            $stmt->execute([$id]);
            
            $pdo->commit();
            redirect_with_message('edit.php?id=' . $id, 'Employee access has been reactivated successfully.', 'success');
        } catch (Exception $e) {
            $pdo->rollBack();
            redirect_with_message('edit.php?id=' . $id, 'Failed to reactivate employee access.', 'error');
        }
    }

    // Original form submission handler

    foreach (array_keys($requiredFields) as $field) {
        $input[$field] = sanitize_text($_POST[$field] ?? '');
    }
    $input['referral_name'] = sanitize_text($_POST['referral_name'] ?? '');
    $input['last_working_date'] = sanitize_text($_POST['last_working_date'] ?? '');
    $input['reason_for_leaving'] = sanitize_text($_POST['reason_for_leaving'] ?? '');
    $input['new_password'] = sanitize_text($_POST['new_password'] ?? '');
    $input['confirm_password'] = sanitize_text($_POST['confirm_password'] ?? '');

    $dateFields = ['dob' => 'Date of birth', 'date_of_joining' => 'Date of joining'];
    foreach ($dateFields as $field => $label) {
        $normalized = normalize_date($input[$field]);
        $input[$field] = $normalized ?? '';
    }

    if ($input['last_working_date'] !== '') {
        $normalizedExit = normalize_date($input['last_working_date']);
        if ($normalizedExit === null) {
            $errors['last_working_date'] = 'Last working date must be a valid date (YYYY-MM-DD)';
        } else {
            $input['last_working_date'] = $normalizedExit;
        }
    }

    $errors = validate_required($requiredFields, $input);

    if ($input['email'] && !filter_var($input['email'], FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = 'Invalid email format';
    }

    if (!preg_match('/^\d{10}$/', $input['phone'])) {
        $errors['phone'] = 'Contact number must be exactly 10 digits';
    }

    // Check for duplicate phone number (excluding current employee)
    if ($input['phone'] !== $emp['phone']) {
        $stmt = $pdo->prepare('SELECT id FROM employees WHERE phone = ? AND id != ? AND deleted_at IS NULL LIMIT 1');
        $stmt->execute([$input['phone'], $id]);
        if ($stmt->fetch()) {
            $errors['phone'] = 'This contact number is already registered with another employee';
        }
    }

    // Check for duplicate email (excluding current employee)
    if ($input['email'] !== $emp['email']) {
        $stmt = $pdo->prepare('SELECT id FROM employees WHERE email = ? AND id != ? AND deleted_at IS NULL LIMIT 1');
        $stmt->execute([$input['email'], $id]);
        if ($stmt->fetch()) {
            $errors['email'] = 'This email is already registered with another employee';
        }
    }

    // Validate password if provided
    if ($input['new_password'] !== '') {
        if (strlen($input['new_password']) < 8) {
            $errors['new_password'] = 'Password must be at least 8 characters long';
        } elseif ($input['new_password'] !== $input['confirm_password']) {
            $errors['confirm_password'] = 'Passwords do not match';
        }
    }

    if (empty($departments)) {
        $errors['department'] = 'No departments configured. Please add one in Admin > Departments.';
        error_log("ERROR: $id - No departments available. Super admin: " . (is_super_admin() ? 'yes' : 'no'));
    } elseif (!in_array($input['department'], $departments, true)) {
        $errors['department'] = 'You cannot assign to this department. Allowed: ' . implode(', ', $departments) . ' | Selected: ' . $input['department'];
        error_log("ERROR: $id - Department not in allowed list. Departments: " . json_encode($departments) . " Selected: " . $input['department']);
    }

    $selectedDesignationId = (int) ($input['designation_id'] ?? 0);
    $allowedDesignationIds = $designationActiveIds;
    if ($currentDesignationId && !in_array($currentDesignationId, $allowedDesignationIds, true)) {
        $allowedDesignationIds[] = $currentDesignationId;
    }
    if (empty($designationActiveIds) && !$currentDesignationId) {
        $errors['designation_id'] = 'No designations configured. Add one in Admin > Designations.';
    } elseif (!$selectedDesignationId || !in_array($selectedDesignationId, $allowedDesignationIds, true)) {
        $errors['designation_id'] = 'Please select a valid designation';
    }

    if (!preg_match('/^[A-Za-z ]+$/', $input['mother_name'])) {
        $errors['mother_name'] = "Mother's name should contain only letters and spaces";
    }

    if (!preg_match('/^[A-Za-z ]+$/', $input['emergency_contact_name'])) {
        $errors['emergency_contact_name'] = 'Emergency contact name should contain only letters and spaces';
    }

    if (!preg_match('/^\d{10}$/', $input['emergency_contact_number'])) {
        $errors['emergency_contact_number'] = 'Emergency contact number must be 10 digits';
    }

    if (!in_array($input['emergency_contact_relation'], $emergencyRelations, true)) {
        $errors['emergency_contact_relation'] = 'Select a valid emergency contact relation';
    }

    $maritalAllowed = $appendCurrentOption($maritalStatusOptions, $emp['marital_status'] ?? '');
    if (!in_array($input['marital_status'], $maritalAllowed, true)) {
        $errors['marital_status'] = 'Select a valid marital status';
    }

    $genderAllowed = $appendCurrentOption($genderOptions, $emp['gender'] ?? '');
    if (!in_array($input['gender'], $genderAllowed, true)) {
        $errors['gender'] = 'Select a valid gender';
    }

    $bloodAllowed = $appendCurrentOption($bloodGroupOptions, $emp['blood_group'] ?? '');
    if (!in_array($input['blood_group'], $bloodAllowed, true)) {
        $errors['blood_group'] = 'Select a valid blood group';
    }

    $qualificationAllowed = $appendCurrentOption($qualificationOptions, $emp['highest_qualification'] ?? '');
    if (!in_array($input['highest_qualification'], $qualificationAllowed, true)) {
        $errors['highest_qualification'] = 'Select a valid qualification';
    }

    if (!in_array($input['employee_status'], $statusOptions, true)) {
        $errors['employee_status'] = 'Please select a valid status';
    }

    $validReferrers = ['consultancy', 'person', 'walkin'];
    if (!in_array($input['referred_by'], $validReferrers, true)) {
        $errors['referred_by'] = 'Please select how this candidate was referred';
    } elseif (in_array($input['referred_by'], ['consultancy', 'person'], true) && $input['referral_name'] === '') {
        $errors['referral_name'] = $input['referred_by'] === 'consultancy' ? 'Consultancy name is' : 'Person name is';
    }

    foreach ($dateFields as $field => $label) {
        if ($input[$field] === '') {
            $errors[$field] = $label . ' must be a valid date (YYYY-MM-DD)';
        }
    }

    if ($input['employee_status'] === 'Active') {
        $input['last_working_date'] = null;
        $input['reason_for_leaving'] = '';
    }

    $config = app_config();
    $docMimes = $config['security']['allowed_doc_mimes'];
    $photoMimes = $config['security']['allowed_photo_mimes'];

    $uploads = [];
    $filesToProcess = [
        'aadhaar' => ['mimes' => $docMimes, 'size' => $config['uploads']['max_size']],
        'aadhaar_front' => ['mimes' => $docMimes, 'size' => $config['uploads']['max_size']],
        'aadhaar_back' => ['mimes' => $docMimes, 'size' => $config['uploads']['max_size']],
        'pan' => ['mimes' => $docMimes, 'size' => $config['uploads']['max_size']],
        'qualification' => ['mimes' => $docMimes, 'size' => $config['uploads']['max_size']],
        'tenth_marksheet' => ['mimes' => $docMimes, 'size' => $config['uploads']['max_size']],
        'twelfth_marksheet' => ['mimes' => $docMimes, 'size' => $config['uploads']['max_size']],
        'bank_proof' => ['mimes' => $docMimes, 'size' => $config['uploads']['max_size']],
        'photo' => ['mimes' => $photoMimes, 'size' => $config['uploads']['photo_max_size']],
    ];

    foreach ($filesToProcess as $field => $rule) {
        $fileError = isset($_FILES[$field]) ? ($_FILES[$field]['error'] ?? UPLOAD_ERR_NO_FILE) : UPLOAD_ERR_NO_FILE;
        if ($fileError === UPLOAD_ERR_NO_FILE) {
            continue; // Keep existing file if none uploaded
        }

        // Use the (possibly updated) name+phone from the submitted form as the file prefix.
        $uploadPrefix = make_upload_prefix($input['first_name'] ?? '', $input['last_name'] ?? '', $input['phone'] ?? '');
        $result = handle_upload($field, $rule['mimes'], $rule['size'], $uploadPrefix);
        if (!empty($result['error'])) {
            foreach ($uploads as $uploaded) {
                @unlink($uploaded);
            }
            redirect_with_message('edit.php?id=' . $id, 'Please fix the highlighted errors and try again.', 'error', [
                'errors' => array_merge($errors, [$field => ucfirst($field) . ': ' . $result['error']]),
                'old' => array_merge($input, ['id' => $id]),
            ]);
        }
        $uploads[$field] = $result['path'];
    }

    if (!empty($errors)) {
        foreach ($uploads as $uploaded) {
            @unlink($uploaded);
        }
        // Log all errors for debugging
        error_log("FORM VALIDATION ERRORS on employee $id: " . json_encode($errors));
        redirect_with_message('edit.php?id=' . $id, 'Please fix the highlighted errors: ' . implode(' | ', $errors), 'error', [
            'errors' => $errors,
            'old' => array_merge($input, ['id' => $id]),
        ]);
    }

    $data = [
        'first_name' => $input['first_name'],
        'last_name' => $input['last_name'],
        'mother_name' => $input['mother_name'],
        'email' => $input['email'],
        'phone' => $input['phone'],
        'emergency_contact' => $input['emergency_contact_number'],
        'emergency_contact_name' => $input['emergency_contact_name'],
        'emergency_contact_number' => $input['emergency_contact_number'],
        'emergency_contact_relation' => $input['emergency_contact_relation'],
        'dob' => $input['dob'],
        'date_of_joining' => $input['date_of_joining'],
        'address' => $input['address'],
        'permanent_address' => $input['permanent_address'],
        'city' => $emp['city'] ?? '',
        'state' => $emp['state'] ?? '',
        'zip' => $input['zip'],
        'aadhaar_number' => $input['aadhaar_number'],
        'pan_number' => $input['pan_number'],
        'highest_qualification' => $input['highest_qualification'],
        'department' => $input['department'],
        'designation_id' => $selectedDesignationId ?: null,
        'employee_status' => $input['employee_status'],
        'last_working_date' => $input['last_working_date'] ?: null,
        'reason_for_leaving' => $input['reason_for_leaving'] ?: null,
        'marital_status' => $input['marital_status'],
        'gender' => $input['gender'],
        'identity_mark' => $input['identity_mark'],
        'blood_group' => $input['blood_group'],
        'referred_by' => $input['referred_by'],
        'referral_name' => $input['referral_name'] ?: null,
        'account_number' => $input['account_number'],
        'ifsc_code' => $input['ifsc_code'],
        'bank_name' => $input['bank_name'],
    ];

    $finalAadhaarPaths = [
        'front' => $uploads['aadhaar_front'] ?? null,
        'back' => $uploads['aadhaar_back'] ?? null,
        'single' => $uploads['aadhaar'] ?? null,
    ];

    // Preserve existing Aadhaar files when not replaced
    foreach (['front', 'back', 'single'] as $key) {
        if (empty($finalAadhaarPaths[$key]) && !empty($aadhaarPaths[$key])) {
            $finalAadhaarPaths[$key] = $aadhaarPaths[$key];
        }
    }

    $data['aadhaar_path'] = compose_aadhaar_value($finalAadhaarPaths);

    foreach ($docColumns as $field => $col) {
        if ($field === 'aadhaar') {
            continue; // handled via compose_aadhaar_value
        }
        $data[$col] = $uploads[$field] ?? $emp[$col];
    }

    $setClause = implode(', ', array_map(fn($col) => $col . ' = :' . $col, array_keys($data)));
    $sql = 'UPDATE employees SET ' . $setClause . ' WHERE id = :id';
    try {
        $stmt = $pdo->prepare($sql);
        $result = $stmt->execute(array_merge($data, ['id' => $id]));
        error_log("Database update for employee $id: " . ($result ? 'SUCCESS' : 'FAILED - execute returned false'));
    } catch (Exception $e) {
        error_log("Database error updating employee $id: " . $e->getMessage());
        redirect_with_message('edit.php?id=' . $id, 'Database error: ' . $e->getMessage(), 'error', [
            'old' => array_merge($input, ['id' => $id]),
        ]);
    }

    // Update password if provided
    if ($input['new_password'] !== '') {
        ensure_employee_auth_table();
        $passwordHash = password_hash($input['new_password'], PASSWORD_BCRYPT, ['cost' => 12]);
        
        // Check if employee already has auth record
        $checkStmt = $pdo->prepare('SELECT id FROM employee_auth WHERE employee_id = ? LIMIT 1');
        $checkStmt->execute([$id]);
        $authExists = $checkStmt->fetch();
        
        if ($authExists) {
            // Update existing password
            $updateStmt = $pdo->prepare('UPDATE employee_auth SET password_hash = :hash, must_change_password = 0, updated_at = NOW() WHERE employee_id = :employee_id');
        } else {
            // Create new auth record
            $updateStmt = $pdo->prepare('INSERT INTO employee_auth (employee_id, password_hash, must_change_password, is_active) VALUES (:employee_id, :hash, 0, 1)');
        }
        $updateStmt->execute(['employee_id' => $id, 'hash' => $passwordHash]);
    }

    // Remove replaced files
    // Remove replaced files while keeping untouched originals
    foreach ($uploads as $field => $newPath) {
        if ($field === 'aadhaar_front') {
            $oldPath = $aadhaarPaths['front'] ?? null;
        } elseif ($field === 'aadhaar_back') {
            $oldPath = $aadhaarPaths['back'] ?? null;
        } elseif ($field === 'aadhaar') {
            $oldPath = $aadhaarPaths['single'] ?? null;
        } else {
            $oldPath = $emp[$docColumns[$field]] ?? null;
        }

        if ($oldPath && $newPath && $oldPath !== $newPath && file_exists($oldPath)) {
            @unlink($oldPath);
        }
    }

    redirect_with_message('view.php?id=' . $id, 'Record updated successfully.');
}

function e(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Edit Record</title>
    <link rel="stylesheet" href="../assets/css/style.css" />
    <link rel="stylesheet" href="../assets/css/polish.css">
</head>
<body class="dashboard-layout">
<div class="app-wrapper">
    <!-- Include Sidebar -->
    <?php require '_sidebar.php'; ?>

    <!-- MAIN CONTENT -->
    <div class="main-content">
        <!-- Top Bar -->
        <div class="top-bar">
            <div class="top-bar-left">
                <button class="sidebar-toggle" id="sidebarToggle" aria-label="Toggle sidebar">?</button>
                <div>
                    <h1 class="page-title">Edit Employee</h1>
                    <div class="breadcrumb-nav">
                        <span>Update details or documents</span>
                    </div>
                </div>
            </div>
            <div class="top-bar-right">
                <a href="dashboard.php" style="color: #cbd5e1; text-decoration: none; padding: 8px 12px; border-radius: 6px; transition: background 0.15s; font-size: 13px; font-weight: 600;" title="Back to Dashboard">? Dashboard</a>
            </div>
        </div>

        <!-- Page Content -->
        <div class="dashboard-container" style="max-width: 1200px;">

    <?php if ($flash): ?>
        <div class="alert <?php echo $flash['type'] === 'error' ? 'alert-error' : 'alert-success'; ?>">
            <?php echo e($flash['message']); ?>
        </div>
    <?php endif; ?>

    <div class="card">
        <form action="edit.php?id=<?php echo $id; ?>" method="post" enctype="multipart/form-data" novalidate>
            <input type="hidden" name="csrf_token" value="<?php echo csrf_token(); ?>" />
            <input type="hidden" name="id" value="<?php echo $id; ?>" />

            <h3 class="section-title">Personal Details</h3>
            <div class="form-grid">
                <div>
                    <label for="first_name">Full Name</label>
                    <input id="first_name" name="first_name" type="text" class="<?php echo !empty($errors['first_name']) ? 'input-invalid' : ''; ?>" value="<?php echo e($form['first_name'] ?? ''); ?>" />
                    <p class="error"><?php echo e($errors['first_name'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="last_name">Father's Name</label>
                    <input id="last_name" name="last_name" type="text" class="<?php echo !empty($errors['last_name']) ? 'input-invalid' : ''; ?>" value="<?php echo e($form['last_name'] ?? ''); ?>" />
                    <p class="error"><?php echo e($errors['last_name'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="mother_name">Mother's Name</label>
                    <input id="mother_name" name="mother_name" type="text" class="<?php echo !empty($errors['mother_name']) ? 'input-invalid' : ''; ?>" value="<?php echo e($form['mother_name'] ?? ''); ?>" />
                    <p class="error"><?php echo e($errors['mother_name'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="email">Email</label>
                    <input id="email" name="email" type="email" class="<?php echo !empty($errors['email']) ? 'input-invalid' : ''; ?>" value="<?php echo e($form['email'] ?? ''); ?>" />
                    <p class="error"><?php echo e($errors['email'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="phone">Contact Number</label>
                    <input id="phone" name="phone" type="tel" class="<?php echo !empty($errors['phone']) ? 'input-invalid' : ''; ?>" value="<?php echo e($form['phone'] ?? ''); ?>" />
                    <p class="error"><?php echo e($errors['phone'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="new_password">Change Password <span style="font-size: 12px; color: #9ca3af;">(Leave empty to keep current password)</span></label>
                    <input id="new_password" name="new_password" type="password" class="<?php echo !empty($errors['new_password']) ? 'input-invalid' : ''; ?>" placeholder="Minimum 8 characters" />
                    <p class="error"><?php echo e($errors['new_password'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="confirm_password">Confirm Password</label>
                    <input id="confirm_password" name="confirm_password" type="password" class="<?php echo !empty($errors['confirm_password']) ? 'input-invalid' : ''; ?>" placeholder="Re-enter password" />
                    <p class="error"><?php echo e($errors['confirm_password'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="emergency_contact_name">Emergency Contact Name</label>
                    <input id="emergency_contact_name" name="emergency_contact_name" type="text" class="<?php echo !empty($errors['emergency_contact_name']) ? 'input-invalid' : ''; ?>" value="<?php echo e($form['emergency_contact_name'] ?? ''); ?>" />
                    <p class="error"><?php echo e($errors['emergency_contact_name'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="emergency_contact_number">Emergency Contact Number</label>
                    <input id="emergency_contact_number" name="emergency_contact_number" type="tel" class="<?php echo !empty($errors['emergency_contact_number']) ? 'input-invalid' : ''; ?>" value="<?php echo e($form['emergency_contact_number'] ?? ''); ?>" />
                    <p class="error"><?php echo e($errors['emergency_contact_number'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="emergency_contact_relation">Relationship with Employee</label>
                    <select id="emergency_contact_relation" name="emergency_contact_relation" class="<?php echo !empty($errors['emergency_contact_relation']) ? 'input-invalid' : ''; ?>">
                        <option value="">Select relation</option>
                        <?php foreach ($emergencyRelations as $relation): ?>
                            <option value="<?php echo e($relation); ?>" <?php echo (isset($form['emergency_contact_relation']) && $form['emergency_contact_relation'] === $relation) ? 'selected' : ''; ?>><?php echo e($relation); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <p class="error"><?php echo e($errors['emergency_contact_relation'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="dob">Date of Birth</label>
                    <input id="dob" name="dob" type="date" class="<?php echo !empty($errors['dob']) ? 'input-invalid' : ''; ?>" value="<?php echo e($form['dob'] ?? ''); ?>" />
                    <p class="error"><?php echo e($errors['dob'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="date_of_joining">Date of Joining</label>
                    <input id="date_of_joining" name="date_of_joining" type="date" class="<?php echo !empty($errors['date_of_joining']) ? 'input-invalid' : ''; ?>" value="<?php echo e($form['date_of_joining'] ?? ''); ?>" />
                    <p class="error"><?php echo e($errors['date_of_joining'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="pan_number">PAN Number</label>
                    <input id="pan_number" name="pan_number" type="text" class="<?php echo !empty($errors['pan_number']) ? 'input-invalid' : ''; ?>" value="<?php echo e($form['pan_number'] ?? ''); ?>" />
                    <p class="error"><?php echo e($errors['pan_number'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="aadhaar_number">UIDAI / Aadhaar Number</label>
                    <input id="aadhaar_number" name="aadhaar_number" type="text" class="<?php echo !empty($errors['aadhaar_number']) ? 'input-invalid' : ''; ?>" value="<?php echo e($form['aadhaar_number'] ?? ''); ?>" />
                    <p class="error"><?php echo e($errors['aadhaar_number'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="highest_qualification">Highest Qualification</label>
                    <select id="highest_qualification" name="highest_qualification" class="<?php echo !empty($errors['highest_qualification']) ? 'input-invalid' : ''; ?>">
                        <option value="">Select qualification</option>
                        <?php foreach ($qualificationChoices as $qual): ?>
                            <option value="<?php echo e($qual); ?>" <?php echo (isset($form['highest_qualification']) && $form['highest_qualification'] === $qual) ? 'selected' : ''; ?>><?php echo e($qual); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <p class="error"><?php echo e($errors['highest_qualification'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="department">Department / Process</label>
                    <select id="department" name="department" class="<?php echo !empty($errors['department']) ? 'input-invalid' : ''; ?>">
                        <option value="">Select department</option>
                        <?php foreach ($departments as $dept): ?>
                            <option value="<?php echo e($dept); ?>" <?php echo (isset($form['department']) && $form['department'] === $dept) ? 'selected' : ''; ?>><?php echo e($dept); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <p class="error"><?php echo e($errors['department'] ?? ''); ?></p>
                    <?php if (empty($departments)): ?>
                        <p class="helper">No departments configured. Add one in Admin &gt; Departments.</p>
                    <?php endif; ?>
                </div>
                <div>
                    <label for="designation_id">Designation</label>
                    <select id="designation_id" name="designation_id" class="<?php echo !empty($errors['designation_id']) ? 'input-invalid' : ''; ?>">
                        <option value="">Select designation</option>
                        <?php foreach ($designationOptions as $desig): ?>
                            <?php $label = $desig['name'] . ($desig['status'] === 'inactive' ? ' (Inactive)' : ''); ?>
                            <option value="<?php echo (int) $desig['id']; ?>" <?php echo (isset($form['designation_id']) && (int) $form['designation_id'] === (int) $desig['id']) ? 'selected' : ''; ?>><?php echo e($label); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <p class="error"><?php echo e($errors['designation_id'] ?? ''); ?></p>
                    <?php if (empty($designationOptions)): ?>
                        <p class="helper">No designations configured. Add one in Admin &gt; Designations.</p>
                    <?php endif; ?>
                </div>
                <div>
                    <label for="employee_status">Employee Status</label>
                    <select id="employee_status" name="employee_status" class="<?php echo !empty($errors['employee_status']) ? 'input-invalid' : ''; ?>">
                        <?php foreach ($statusOptions as $status): ?>
                            <option value="<?php echo e($status); ?>" <?php echo (isset($form['employee_status']) ? $form['employee_status'] : 'Active') === $status ? 'selected' : ''; ?>><?php echo e($status); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <p class="error"><?php echo e($errors['employee_status'] ?? ''); ?></p>
                </div>
                <div data-status-extra style="display:none;">
                    <label for="last_working_date">Last Working Date</label>
                    <input id="last_working_date" name="last_working_date" type="date" class="<?php echo !empty($errors['last_working_date']) ? 'input-invalid' : ''; ?>" value="<?php echo e($form['last_working_date'] ?? ''); ?>" />
                    <p class="error"><?php echo e($errors['last_working_date'] ?? ''); ?></p>
                </div>
                <div data-status-extra style="display:none;">
                    <label for="reason_for_leaving">Reason for Leaving</label>
                    <textarea id="reason_for_leaving" name="reason_for_leaving" rows="2" class="<?php echo !empty($errors['reason_for_leaving']) ? 'input-invalid' : ''; ?>" placeholder="Optional"><?php echo e($form['reason_for_leaving'] ?? ''); ?></textarea>
                    <p class="error"><?php echo e($errors['reason_for_leaving'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="marital_status">Marital Status</label>
                    <select id="marital_status" name="marital_status" class="<?php echo !empty($errors['marital_status']) ? 'input-invalid' : ''; ?>">
                        <option value="">Select marital status</option>
                        <?php foreach ($maritalStatusChoices as $status): ?>
                            <option value="<?php echo e($status); ?>" <?php echo (isset($form['marital_status']) && $form['marital_status'] === $status) ? 'selected' : ''; ?>><?php echo e($status); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <p class="error"><?php echo e($errors['marital_status'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="gender">Gender</label>
                    <select id="gender" name="gender" class="<?php echo !empty($errors['gender']) ? 'input-invalid' : ''; ?>">
                        <option value="">Select gender</option>
                        <?php foreach ($genderChoices as $gender): ?>
                            <option value="<?php echo e($gender); ?>" <?php echo (isset($form['gender']) && $form['gender'] === $gender) ? 'selected' : ''; ?>><?php echo e($gender); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <p class="error"><?php echo e($errors['gender'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="identity_mark">Identity Mark</label>
                    <input id="identity_mark" name="identity_mark" type="text" class="<?php echo !empty($errors['identity_mark']) ? 'input-invalid' : ''; ?>" value="<?php echo e($form['identity_mark'] ?? ''); ?>" />
                    <p class="error"><?php echo e($errors['identity_mark'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="blood_group">Blood Group</label>
                    <select id="blood_group" name="blood_group" class="<?php echo !empty($errors['blood_group']) ? 'input-invalid' : ''; ?>">
                        <option value="">Select blood group</option>
                        <?php foreach ($bloodGroupChoices as $blood): ?>
                            <option value="<?php echo e($blood); ?>" <?php echo (isset($form['blood_group']) && $form['blood_group'] === $blood) ? 'selected' : ''; ?>><?php echo e($blood); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <p class="error"><?php echo e($errors['blood_group'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="address">Present Address</label>
                    <textarea id="address" name="address" rows="2" class="<?php echo !empty($errors['address']) ? 'input-invalid' : ''; ?>"><?php echo e($form['address'] ?? ''); ?></textarea>
                    <p class="error"><?php echo e($errors['address'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="permanent_address">Permanent Address</label>
                    <textarea id="permanent_address" name="permanent_address" rows="2" class="<?php echo !empty($errors['permanent_address']) ? 'input-invalid' : ''; ?>"><?php echo e($form['permanent_address'] ?? ''); ?></textarea>
                    <p class="error"><?php echo e($errors['permanent_address'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="zip">Present ZIP / PIN</label>
                    <input id="zip" name="zip" type="text" class="<?php echo !empty($errors['zip']) ? 'input-invalid' : ''; ?>" value="<?php echo e($form['zip'] ?? ''); ?>" />
                    <p class="error"><?php echo e($errors['zip'] ?? ''); ?></p>
                </div>
            </div>

            <hr style="margin: 20px 0; border: none; border-top: 1px solid #e5e7eb;" />

            <h3 class="section-title">Bank Details</h3>
            <div class="form-grid">
                <div>
                    <label for="account_number">Account Number</label>
                    <input id="account_number" name="account_number" type="text" class="<?php echo !empty($errors['account_number']) ? 'input-invalid' : ''; ?>" value="<?php echo e($form['account_number'] ?? ''); ?>" />
                    <p class="error"><?php echo e($errors['account_number'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="ifsc_code">IFSC Code</label>
                    <input id="ifsc_code" name="ifsc_code" type="text" class="<?php echo !empty($errors['ifsc_code']) ? 'input-invalid' : ''; ?>" value="<?php echo e($form['ifsc_code'] ?? ''); ?>" />
                    <p class="error"><?php echo e($errors['ifsc_code'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="bank_name">Bank Name</label>
                    <input id="bank_name" name="bank_name" type="text" class="<?php echo !empty($errors['bank_name']) ? 'input-invalid' : ''; ?>" value="<?php echo e($form['bank_name'] ?? ''); ?>" />
                    <p class="error"><?php echo e($errors['bank_name'] ?? ''); ?></p>
                </div>
            </div>

            <hr style="margin: 20px 0; border: none; border-top: 1px solid #e5e7eb;" />

            <h3 class="section-title">Referral Details</h3>
            <div class="form-grid">
                <div>
                    <label for="referred_by">Referred By</label>
                    <select id="referred_by" name="referred_by" class="<?php echo !empty($errors['referred_by']) ? 'input-invalid' : ''; ?>">
                        <option value="">Select an option</option>
                        <option value="consultancy" <?php echo (isset($form['referred_by']) && $form['referred_by'] === 'consultancy') ? 'selected' : ''; ?>>Consultancy</option>
                        <option value="person" <?php echo (isset($form['referred_by']) && $form['referred_by'] === 'person') ? 'selected' : ''; ?>>Person</option>
                        <option value="walkin" <?php echo (isset($form['referred_by']) && $form['referred_by'] === 'walkin') ? 'selected' : ''; ?>>Walk-in (Self)</option>
                    </select>
                    <p class="error"><?php echo e($errors['referred_by'] ?? ''); ?></p>
                </div>
                <div data-referral-detail style="display:none;">
                    <label for="referral_name" data-referral-label>Referral Name</label>
                    <input id="referral_name" name="referral_name" type="text" class="<?php echo !empty($errors['referral_name']) ? 'input-invalid' : ''; ?>" value="<?php echo e($form['referral_name'] ?? ''); ?>" />
                    <p class="error"><?php echo e($errors['referral_name'] ?? ''); ?></p>
                </div>
            </div>

            <hr style="margin: 20px 0; border: none; border-top: 1px solid #e5e7eb;" />

            <h3 class="section-title">Documents</h3>
            <p class="helper">Upload a new file to replace the existing document. Leave blank to keep the current file.</p>
            <?php if (!empty($pendingDocs)): ?>
                <p class="helper" style="color:#ef4444;">Pending: <?php echo e(implode(', ', $pendingDocs)); ?></p>
            <?php endif; ?>
            <div class="form-grid">
                <div>
                    <label for="aadhaar_front">Aadhaar Front</label>
                    <input id="aadhaar_front" name="aadhaar_front" type="file" accept="application/pdf,image/jpeg,image/png" class="<?php echo !empty($errors['aadhaar_front']) ? 'input-invalid' : ''; ?>" />
                    <?php $aadhaarFrontPath = $aadhaarPaths['front'] ?? null; $aadhaarFrontHasFile = (bool) resolve_upload_path($aadhaarFrontPath); ?>
                    <p class="helper">
                        <?php if ($aadhaarFrontHasFile): ?>
                            Current: <a href="download.php?id=<?php echo $id; ?>&type=aadhaar_front" target="_blank">Download</a>
                        <?php else: ?>
                            Optional: upload the front side (PDF/JPG/PNG, max 5 MB)
                        <?php endif; ?>
                    </p>
                    <p class="error"><?php echo e($errors['aadhaar_front'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="aadhaar_back">Aadhaar Back</label>
                    <input id="aadhaar_back" name="aadhaar_back" type="file" accept="application/pdf,image/jpeg,image/png" class="<?php echo !empty($errors['aadhaar_back']) ? 'input-invalid' : ''; ?>" />
                    <?php $aadhaarBackPath = $aadhaarPaths['back'] ?? null; $aadhaarBackHasFile = (bool) resolve_upload_path($aadhaarBackPath); ?>
                    <p class="helper">
                        <?php if ($aadhaarBackHasFile): ?>
                            Current: <a href="download.php?id=<?php echo $id; ?>&type=aadhaar_back" target="_blank">Download</a>
                        <?php else: ?>
                            Optional: upload the back side (PDF/JPG/PNG, max 5 MB)
                        <?php endif; ?>
                    </p>
                    <p class="error"><?php echo e($errors['aadhaar_back'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="pan">PAN Document</label>
                    <input id="pan" name="pan" type="file" accept="application/pdf,image/jpeg,image/png" class="<?php echo !empty($errors['pan']) ? 'input-invalid' : ''; ?>" />
                    <?php $panHasFile = (bool) resolve_upload_path($emp['pan_path'] ?? null); ?>
                    <p class="helper">
                        <?php if ($panHasFile): ?>
                            Current: <a href="download.php?id=<?php echo $id; ?>&type=pan" target="_blank">Download</a>
                        <?php else: ?>
                            Not uploaded yet (pending)
                        <?php endif; ?>
                    </p>
                    <p class="error"><?php echo e($errors['pan'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="qualification">Graduation</label>
                    <input id="qualification" name="qualification" type="file" accept="application/pdf,image/jpeg,image/png" class="<?php echo !empty($errors['qualification']) ? 'input-invalid' : ''; ?>" />
                    <?php $qualificationHasFile = (bool) resolve_upload_path($emp['qualification_path'] ?? null); ?>
                    <p class="helper">
                        <?php if ($qualificationHasFile): ?>
                            Current: <a href="download.php?id=<?php echo $id; ?>&type=qualification" target="_blank">Download</a>
                        <?php else: ?>
                            Optional
                        <?php endif; ?>
                    </p>
                    <p class="error"><?php echo e($errors['qualification'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="tenth_marksheet">10th Marksheet</label>
                    <input id="tenth_marksheet" name="tenth_marksheet" type="file" accept="application/pdf,image/jpeg,image/png" class="<?php echo !empty($errors['tenth_marksheet']) ? 'input-invalid' : ''; ?>" />
                    <?php $tenthHasFile = (bool) resolve_upload_path($emp['tenth_marksheet_path'] ?? null); ?>
                    <p class="helper">
                        <?php if ($tenthHasFile): ?>
                            Current: <a href="download.php?id=<?php echo $id; ?>&type=tenth_marksheet" target="_blank">Download</a>
                        <?php else: ?>
                            Not uploaded yet (mandatory)
                        <?php endif; ?>
                    </p>
                    <p class="error"><?php echo e($errors['tenth_marksheet'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="twelfth_marksheet">12th Marksheet</label>
                    <input id="twelfth_marksheet" name="twelfth_marksheet" type="file" accept="application/pdf,image/jpeg,image/png" class="<?php echo !empty($errors['twelfth_marksheet']) ? 'input-invalid' : ''; ?>" />
                    <?php $twelfthHasFile = (bool) resolve_upload_path($emp['twelfth_marksheet_path'] ?? null); ?>
                    <p class="helper">
                        <?php if ($twelfthHasFile): ?>
                            Current: <a href="download.php?id=<?php echo $id; ?>&type=twelfth_marksheet" target="_blank">Download</a>
                        <?php else: ?>
                            Not uploaded yet (mandatory)
                        <?php endif; ?>
                    </p>
                    <p class="error"><?php echo e($errors['twelfth_marksheet'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="bank_proof">Bank Proof</label>
                    <input id="bank_proof" name="bank_proof" type="file" accept="application/pdf,image/jpeg,image/png" class="<?php echo !empty($errors['bank_proof']) ? 'input-invalid' : ''; ?>" />
                    <?php $bankProofHasFile = (bool) resolve_upload_path($emp['bank_proof_path'] ?? null); ?>
                    <p class="helper">
                        <?php if ($bankProofHasFile): ?>
                            Current: <a href="download.php?id=<?php echo $id; ?>&type=bank_proof" target="_blank">Download</a>
                        <?php else: ?>
                            Not uploaded yet (pending)
                        <?php endif; ?>
                    </p>
                    <p class="error"><?php echo e($errors['bank_proof'] ?? ''); ?></p>
                </div>
                <div>
                    <label for="photo">Passport Photo</label>
                    <input id="photo" name="photo" type="file" accept="image/jpeg,image/png" class="<?php echo !empty($errors['photo']) ? 'input-invalid' : ''; ?>" />
                    <?php $photoHasFile = (bool) resolve_upload_path($emp['photo_path'] ?? null); ?>
                    <p class="helper">
                        <?php if ($photoHasFile): ?>
                            Current: <a href="download.php?id=<?php echo $id; ?>&type=photo" target="_blank">Download</a>
                        <?php else: ?>
                            Not uploaded yet (pending)
                        <?php endif; ?>
                    </p>
                    <p class="error"><?php echo e($errors['photo'] ?? ''); ?></p>
                </div>
            </div>

            <div style="margin-top: 18px; display: flex; justify-content: flex-end; gap:10px;">
                <button type="button" class="button-ghost" onclick="window.location.href='view.php?id=<?php echo $id; ?>';"><i class="fas fa-times"></i> Cancel</button>
                <button type="submit"><i class="fas fa-save"></i> Save Changes</button>
            </div>

        </form>

        <!-- Employee Access Control Section (outside main form to prevent HTML nesting violation) -->
        <div style="margin-top: 24px; padding: 18px; background-color: #0f172e; border-radius: 8px; border-left: 4px solid #dc2626;">
            <h3 style="margin: 0 0 12px 0; color: #e5e7eb; font-size: 16px; font-weight: 600;">
                <i class="fas fa-lock" style="margin-right: 8px;"></i>Employee Access Control
            </h3>
            <p style="margin: 0 0 18px 0; color: #cbd5e1; font-size: 14px;">
                <?php if ($emp['employee_status'] === 'Active'): ?>
                    This employee is currently active and can access the system.
                <?php else: ?>
                    This employee account is currently inactive (<?php echo e($emp['employee_status']); ?>) and cannot access the system.
                <?php endif; ?>
            </p>
            <div style="display: flex; gap: 10px;">
                <?php if ($emp['employee_status'] === 'Active'): ?>
                    <form method="POST" action="edit.php?id=<?php echo $id; ?>" onsubmit="return confirm('Deactivate this employee\'s access? They will not be able to log in, but their data will be retained.');">
                        <input type="hidden" name="csrf_token" value="<?php echo e(csrf_token()); ?>">
                        <input type="hidden" name="action" value="deactivate">
                        <button type="submit" class="button-ghost" style="border-color: #dc2626; color: #fca5a5;">
                            <i class="fas fa-ban"></i> Deactivate Access
                        </button>
                    </form>
                <?php else: ?>
                    <form method="POST" action="edit.php?id=<?php echo $id; ?>" onsubmit="return confirm('Reactivate this employee\'s access? They will be marked as Active and able to log in.');">
                        <input type="hidden" name="csrf_token" value="<?php echo e(csrf_token()); ?>">
                        <input type="hidden" name="action" value="reactivate">
                        <button type="submit" class="button-ghost" style="border-color: #2563eb; color: #93c5fd;">
                            <i class="fas fa-check-circle"></i> Reactivate Access
                        </button>
                    </form>
                <?php endif; ?>
            </div>
        </div>
    </div>
        </div>
        </div>
    </div>
</div>

<div class="sidebar-overlay" id="sidebarOverlay"></div>

<script>
    // Sidebar Toggle
    const sidebar = document.getElementById('sidebar');
    const sidebarToggle = document.getElementById('sidebarToggle');
    const sidebarOverlay = document.getElementById('sidebarOverlay');

    sidebarToggle?.addEventListener('click', () => {
        sidebar.classList.toggle('open');
        sidebarOverlay.classList.toggle('open');
    });

    sidebarOverlay?.addEventListener('click', () => {
        sidebar.classList.remove('open');
        sidebarOverlay.classList.remove('open');
    });
</script>

<script>
    (function() {
            const form = document.querySelector('form');
            if (!form) return;
            const referralSelect = form.elements['referred_by'];
            const referralDetail = form.querySelector('[data-referral-detail]');
            const referralLabel = form.querySelector('[data-referral-label]');
            const referralInput = form.elements['referral_name'];
            const syncReferral = () => {
                if (!referralSelect || !referralDetail || !referralLabel || !referralInput) return;
                const val = referralSelect.value;
                const needsName = val === 'consultancy' || val === 'person';
                referralDetail.style.display = needsName ? 'block' : 'none';
                referralLabel.textContent = val === 'consultancy' ? 'Consultancy Name' : val === 'person' ? 'Person Name' : 'Referral Name';
                if (!needsName) {
                    referralInput.classList.remove('input-invalid');
                }
            };
            syncReferral();
            referralSelect?.addEventListener('change', syncReferral);

            const statusSelect = form.elements['employee_status'];
            const statusExtras = form.querySelectorAll('[data-status-extra]');
            const syncStatus = () => {
                if (!statusSelect) return;
                const showExtras = statusSelect.value !== 'Active';
                statusExtras.forEach((el) => {
                    el.style.display = showExtras ? 'block' : 'none';
                    if (!showExtras) {
                        const input = el.querySelector('input, textarea');
                        if (input) {
                            input.value = '';
                            input.classList.remove('input-invalid');
                        }
                        const err = el.querySelector('.error');
                        if (err) err.textContent = '';
                    }
                });
            };
            syncStatus();
            statusSelect?.addEventListener('change', syncStatus);

            const attachSearchableSelects = () => {
                const inputs = form.querySelectorAll('[data-searchable-input]');
                inputs.forEach((input) => {
                    const target = input.getAttribute('data-searchable-input');
                    if (!target) return;
                    const select = form.querySelector(`[data-searchable-select="${target}"]`);
                    if (!select) return;
                    const options = Array.from(select.options);
                    input.addEventListener('input', () => {
                        const term = input.value.trim().toLowerCase();
                        options.forEach((opt) => {
                            if (!opt.value) {
                                opt.hidden = false;
                                return;
                            }
                            opt.hidden = term ? opt.text.toLowerCase().indexOf(term) === -1 : false;
                        });
                    });
                });
            };
            attachSearchableSelects();
        })();
    </script>
</body>
</html>



← Back to Directory Edit File 🔒 Chmod

WP File Manager