<?php
// edit_employee.php

ini_set('display_errors', 0);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');

session_start();

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

require_once("../config/config.php"); // $conn = mysqli connection

$employee_id = $_GET['id'] ?? '';
if (empty($employee_id)) {
    die("Invalid employee ID.");
}

$success = $error = "";

// Fetch existing employee
$stmt = $conn->prepare("SELECT * FROM employee_master WHERE employee_id = ? AND status = 'active'");
$stmt->bind_param("s", $employee_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    die("Employee not found.");
}

$emp = $result->fetch_assoc();
$stmt->close();

// AJAX: Add Designation or Education (same as add page)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        echo json_encode(['success' => false, 'message' => 'Invalid CSRF token']);
        exit;
    }

    $action = $_POST['action'];
    $name = trim($_POST['name'] ?? '');

    if (empty($name)) {
        echo json_encode(['success' => false, 'message' => 'Name is required']);
        exit;
    }

    if ($action === 'add_designation') {
        $table = 'designation_master';
        $field = 'designation_name';
    } elseif ($action === 'add_education') {
        $table = 'education_master';
        $field = 'education_name';
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        exit;
    }

    // Check duplicate
    $check = $conn->prepare("SELECT id FROM $table WHERE $field = ? AND status = 'active'");
    $check->bind_param("s", $name);
    $check->execute();
    if ($check->get_result()->num_rows > 0) {
        echo json_encode(['success' => false, 'message' => ucfirst(str_replace('_', ' ', $action)) . ' already exists']);
        $check->close();
        exit;
    }
    $check->close();

    // Insert
    $stmt = $conn->prepare("INSERT INTO $table ($field, status) VALUES (?, 'active')");
    $stmt->bind_param("s", $name);
    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Added successfully!', 'value' => $name]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Database error']);
    }
    $stmt->close();
    exit;
}

// Main Form Submission - UPDATE
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['action'])) {
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        $error = "Invalid request.";
    } else {
        $required = ['first_name', 'last_name', 'full_name', 'date_of_joining', 'mobile_number', 'designation', 'education'];
        foreach ($required as $field) {
            if (empty(trim($_POST[$field] ?? ''))) {
                $error = "Please fill all required fields.";
                break;
            }
        }

        if (!$error) {
            $upload_dir = "../uploads/employees/" . $employee_id . "/";

            // Handle file uploads (replace if new file uploaded)
            $uploaded = [
                'aadhar_card_file' => $emp['aadhar_card_file'],
                'pan_card_file' => $emp['pan_card_file'],
                'passport_file' => $emp['passport_file'],
                'driving_license_file' => $emp['driving_license_file'],
                'left_hand_thumb_file' => $emp['left_hand_thumb_file'],
                'right_hand_thumb_file' => $emp['right_hand_thumb_file'],
                'other_document_file' => $emp['other_document_file']
            ];

            $files = array_keys($uploaded);
            foreach ($files as $file) {
                if (!empty($_FILES[$file]['name']) && $_FILES[$file]['error'] === UPLOAD_ERR_OK) {
                    $ext = strtolower(pathinfo($_FILES[$file]['name'], PATHINFO_EXTENSION));
                    $allowed = ['jpg', 'jpeg', 'png', 'pdf'];
                    if (in_array($ext, $allowed)) {
                        // Delete old file if exists
                        if ($uploaded[$file] && file_exists("../" . $uploaded[$file])) {
                            unlink("../" . $uploaded[$file]);
                        }

                        $filename = $file . "." . $ext;
                        $target = $upload_dir . $filename;
                        if (move_uploaded_file($_FILES[$file]['tmp_name'], $target)) {
                            $uploaded[$file] = "uploads/employees/{$employee_id}/{$filename}";
                        }
                    }
                }
            }

            // Prepare values
            $date_of_joining = $_POST['date_of_joining'];
            $working_hours = (int)($_POST['working_hours'] ?? 0);

            $first_name = trim($_POST['first_name']);
            $middle_name = trim($_POST['middle_name'] ?? '');
            $last_name = trim($_POST['last_name']);
            $full_name = trim($_POST['full_name']);

            $permanent_address = trim($_POST['permanent_address'] ?? '');
            $post = trim($_POST['post'] ?? '');
            $city_or_village = trim($_POST['city_or_village'] ?? '');
            $taluka = trim($_POST['taluka'] ?? '');
            $district = trim($_POST['district'] ?? '');
            $state = trim($_POST['state'] ?? '');
            $pincode = trim($_POST['pincode'] ?? '');

            $current_address = trim($_POST['current_address'] ?? '');
            $current_post = trim($_POST['current_post'] ?? '');
            $current_city_or_village = trim($_POST['current_city_or_village'] ?? '');
            $current_state = trim($_POST['current_state'] ?? '');
            $current_pincode = trim($_POST['current_pincode'] ?? '');

            $mobile_number = trim($_POST['mobile_number']);
            $alternate_mobile_number = trim($_POST['alternate_mobile_number'] ?? '');
            $aadhar_number = trim($_POST['aadhar_number'] ?? '');
            $pan_number = trim($_POST['pan_number'] ?? '');
            $epf_number = trim($_POST['epf_number'] ?? '');
            $uan_number = trim($_POST['uan_number'] ?? '');
            $esic_number = trim($_POST['esic_number'] ?? '');

            $bank_account_number = trim($_POST['bank_account_number'] ?? '');
            $ifsc_code = trim($_POST['ifsc_code'] ?? '');
            $bank_account_holder_name = trim($_POST['bank_account_holder_name'] ?? '');
            $bank_branch_name = trim($_POST['bank_branch_name'] ?? '');
            $bank_name_and_address = trim($_POST['bank_name_and_address'] ?? '');

            $wages = (float)($_POST['wages'] ?? 0);
            $designation = trim($_POST['designation']);
            $reference = trim($_POST['reference'] ?? '');
            $decided_salary = (float)($_POST['decided_salary'] ?? 0);
            $place_of_work = trim($_POST['place_of_work'] ?? '');
            $unit_head_name = trim($_POST['unit_head_name'] ?? '');
            $work = trim($_POST['work'] ?? '');

            $date_of_birth = $_POST['date_of_birth'] ?? null;
            $blood_group = trim($_POST['blood_group'] ?? '');
            $education = trim($_POST['education']);
            $mother_tongue = trim($_POST['mother_tongue'] ?? '');
            $religion = trim($_POST['religion'] ?? '');
            $marital_status = trim($_POST['marital_status'] ?? '');

            // UPDATE Query
            $sql = "UPDATE employee_master SET
                date_of_joining = ?, working_hours = ?,
                first_name = ?, middle_name = ?, last_name = ?, full_name = ?,
                permanent_address = ?, post = ?, city_or_village = ?, taluka = ?, district = ?, state = ?, pincode = ?,
                current_address = ?, current_post = ?, current_city_or_village = ?, current_state = ?, current_pincode = ?,
                mobile_number = ?, alternate_mobile_number = ?, aadhar_number = ?, pan_number = ?,
                epf_number = ?, uan_number = ?, esic_number = ?,
                bank_account_number = ?, ifsc_code = ?, bank_account_holder_name = ?, bank_branch_name = ?, bank_name_and_address = ?,
                wages = ?, designation = ?, reference = ?, decided_salary = ?, place_of_work = ?, unit_head_name = ?, work = ?,
                date_of_birth = ?, blood_group = ?, education = ?, mother_tongue = ?, religion = ?, marital_status = ?,
                aadhar_card_file = ?, pan_card_file = ?, passport_file = ?, driving_license_file = ?,
                left_hand_thumb_file = ?, right_hand_thumb_file = ?, other_document_file = ?,
                updated_at = NOW()
            WHERE employee_id = ?";

            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                $error = "Prepare failed: " . $conn->error;
            } else {
                $stmt->bind_param(
                    "sisssssssssssssssssssssssssssssssssssssssssssssss",
                    $date_of_joining,
                    $working_hours,
                    $first_name, $middle_name, $last_name, $full_name,
                    $permanent_address, $post, $city_or_village, $taluka, $district, $state, $pincode,
                    $current_address, $current_post, $current_city_or_village, $current_state, $current_pincode,
                    $mobile_number, $alternate_mobile_number, $aadhar_number, $pan_number,
                    $epf_number, $uan_number, $esic_number,
                    $bank_account_number, $ifsc_code, $bank_account_holder_name, $bank_branch_name, $bank_name_and_address,
                    $wages, $designation, $reference, $decided_salary, $place_of_work, $unit_head_name, $work,
                    $date_of_birth, $blood_group, $education, $mother_tongue, $religion, $marital_status,
                    $uploaded['aadhar_card_file'],
                    $uploaded['pan_card_file'],
                    $uploaded['passport_file'],
                    $uploaded['driving_license_file'],
                    $uploaded['left_hand_thumb_file'],
                    $uploaded['right_hand_thumb_file'],
                    $uploaded['other_document_file'],
                    $employee_id
                );

                if ($stmt->execute()) {
                    $success = "Employee <strong>$employee_id</strong> updated successfully!";
                    // Refresh data
                    header("Location: edit_employee.php?id=$employee_id&success=1");
                    exit;
                } else {
                    $error = "Update failed: " . $stmt->error;
                }
                $stmt->close();
            }
        }
    }
}

// Reload fresh data after success redirect
if (isset($_GET['success'])) {
    $stmt = $conn->prepare("SELECT * FROM employee_master WHERE employee_id = ?");
    $stmt->bind_param("s", $employee_id);
    $stmt->execute();
    $emp = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $success = "Employee updated successfully!";
}

// Form Sections
$sections = [
    "Company Information" => [
        "Employee ID" => ["type" => "text", "name" => "employee_id", "readonly" => true, "value" => $employee_id],
        "Date of Joining" => ["type" => "date", "name" => "date_of_joining", "required" => true],
        "Date of Registration" => ["type" => "date", "name" => "date_of_registration", "readonly" => true, "value" => date('Y-m-d')],
        "Working Hours" => ["type" => "number", "name" => "working_hours", "min" => 0, "step" => 1],
    ],
    "Name & Address" => [
        "First Name" => ["type" => "text", "name" => "first_name", "required" => true],
        "Middle Name" => ["type" => "text", "name" => "middle_name"],
        "Last Name" => ["type" => "text", "name" => "last_name", "required" => true],
        "Full Name" => ["type" => "text", "name" => "full_name", "required" => true, "readonly" => true],
        "Permanent Address" => ["type" => "textarea", "name" => "permanent_address"],
        "Post" => ["type" => "text", "name" => "post"],
        "City or Village" => ["type" => "text", "name" => "city_or_village"],
        "Taluka" => ["type" => "text", "name" => "taluka"],
        "District" => ["type" => "text", "name" => "district"],
        "State" => ["type" => "text", "name" => "state"],
        "Pincode" => ["type" => "text", "name" => "pincode"],
        "Current Address" => ["type" => "textarea", "name" => "current_address"],
        "Current Post" => ["type" => "text", "name" => "current_post"],
        "Current City or Village" => ["type" => "text", "name" => "current_city_or_village"],
        "Current State" => ["type" => "text", "name" => "current_state"],
        "Current Pincode" => ["type" => "text", "name" => "current_pincode"],
    ],
    "Contact & Official Details" => [
        "Mobile Number" => ["type" => "tel", "name" => "mobile_number", "required" => true],
        "Alternate Mobile Number" => ["type" => "tel", "name" => "alternate_mobile_number"],
        "Aadhar Number" => ["type" => "text", "name" => "aadhar_number"],
        "PAN Number" => ["type" => "text", "name" => "pan_number"],
        "EPF Number" => ["type" => "text", "name" => "epf_number"],
        "UAN Number" => ["type" => "text", "name" => "uan_number"],
        "ESIC Number" => ["type" => "text", "name" => "esic_number"],
        "Bank Account Number" => ["type" => "text", "name" => "bank_account_number"],
        "IFSC Code" => ["type" => "text", "name" => "ifsc_code"],
        "Bank Account Holder Name" => ["type" => "text", "name" => "bank_account_holder_name"],
        "Bank Branch Name" => ["type" => "text", "name" => "bank_branch_name"],
        "Bank Name & Address" => ["type" => "text", "name" => "bank_name_and_address"],
        "Wages (Per Hour)" => ["type" => "number", "name" => "wages", "step" => "0.01", "min" => 0],
    ],
    "Appointment Details" => [
        "Designation" => [
            "type" => "select_plus",
            "name" => "designation",
            "options_query" => "SELECT designation_name AS value, designation_name AS label FROM designation_master WHERE status = 'active' ORDER BY designation_name",
            "add_new" => "designation",
            "required" => true
        ],
        "Reference" => ["type" => "text", "name" => "reference"],
        "Decided Salary" => ["type" => "number", "name" => "decided_salary", "step" => "0.01", "min" => 0],
        "Place Of Work" => ["type" => "text", "name" => "place_of_work"],
        "Unit Head Name" => ["type" => "text", "name" => "unit_head_name"],
        "Work" => ["type" => "text", "name" => "work"],
    ],
    "Personal Information" => [
        "Date of Birth" => ["type" => "date", "name" => "date_of_birth", "onchange" => "calculateAge(this.value)"],
        "Age" => ["type" => "number", "name" => "age", "readonly" => true, "min" => 0],
        "Blood Group" => ["type" => "text", "name" => "blood_group"],
        "Education" => [
            "type" => "select_plus",
            "name" => "education",
            "options_query" => "SELECT education_name AS value, education_name AS label FROM education_master WHERE status = 'active' ORDER BY education_name",
            "add_new" => "education",
            "required" => true
        ],
        "Mother Tongue" => ["type" => "text", "name" => "mother_tongue"],
        "Religion" => ["type" => "text", "name" => "religion"],
        "Marital Status" => [
            "type" => "select",
            "name" => "marital_status",
            "options" => ["", "Single", "Married", "Divorced", "Widowed"]
        ],
    ],
    "Upload Documents" => [
        "Aadhar Card" => ["type" => "file", "name" => "aadhar_card_file", "accept" => "image/*,.pdf"],
        "PAN Card" => ["type" => "file", "name" => "pan_card_file", "accept" => "image/*,.pdf"],
        "Passport" => ["type" => "file", "name" => "passport_file", "accept" => "image/*,.pdf"],
        "Driving License" => ["type" => "file", "name" => "driving_license_file", "accept" => "image/*,.pdf"],
        "Left Hand Thumb" => ["type" => "file", "name" => "left_hand_thumb_file", "accept" => "image/*"],
        "Right Hand Thumb" => ["type" => "file", "name" => "right_hand_thumb_file", "accept" => "image/*"],
        "Other Document" => ["type" => "file", "name" => "other_document_file", "accept" => "*"],
    ]
];
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Employee - <?= htmlspecialchars($emp['employee_id']) ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
    :root {
        --primary: #8b5cf6;
        --primary-light: #a78bfa;
        --text: #e0e7ff;
        --success: #34d399;
        --error: #f87171;
    }

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: 'Segoe UI', sans-serif;
        min-height: 100vh;
        background: linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)), url('../background.jpeg') center/cover no-repeat fixed;
        color: var(--text);
        padding: 20px;
    }

    .container {
        max-width: 1200px;
        margin: 0 auto;
        background: rgba(255, 255, 255, 0.1);
        backdrop-filter: blur(16px);
        border-radius: 24px;
        border: 1px solid rgba(255, 255, 255, 0.2);
        box-shadow: 0 20px 50px rgba(0, 0, 0, 0.4);
        overflow: hidden;
    }

    .header {
        background: rgba(255, 255, 255, 0.15);
        padding: 40px;
        text-align: center;
    }

    .header h1 {
        font-size: 2.5rem;
        margin-bottom: 10px;
    }

    .form-area {
        padding: 40px;
    }

    .message {
        padding: 16px 20px;
        border-radius: 14px;
        margin-bottom: 30px;
        display: flex;
        align-items: center;
        gap: 12px;
        font-weight: 600;
        backdrop-filter: blur(8px);
    }

    .success {
        background: rgba(52, 211, 153, 0.2);
        border: 1px solid rgba(74, 222, 128, 0.4);
    }

    .error {
        background: rgba(239, 68, 68, 0.2);
        border: 1px solid rgba(252, 165, 165, 0.4);
    }

    .section-title {
        font-size: 1.8rem;
        margin: 50px 0 25px;
        padding-bottom: 12px;
        border-bottom: 1px solid rgba(255, 255, 255, 0.3);
    }

    .form-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
        gap: 24px;
    }

    label {
        display: block;
        margin-bottom: 8px;
        font-weight: 600;
    }

    .required {
        color: #fca5a5;
    }

    input,
    textarea,
    select {
        width: 100%;
        padding: 16px 18px;
        background: rgba(255, 255, 255, 0.15);
        border: 1px solid rgba(255, 255, 255, 0.3);
        border-radius: 14px;
        color: white;
        font-size: 16px;
        transition: all .3s;
    }

    input::placeholder,
    textarea::placeholder {
        color: rgba(255, 255, 255, 0.6);
    }

    input:focus,
    textarea:focus,
    select:focus {
        outline: none;
        border-color: var(--primary-light);
        background: rgba(255, 255, 255, 0.25);
        box-shadow: 0 0 0 4px rgba(167, 139, 250, 0.3);
    }

    textarea {
        height: 120px;
        resize: vertical;
    }

    input[readonly] {
        opacity: 0.8;
        cursor: not-allowed;
    }

    .add-new-group {
        display: flex;
        gap: 12px;
        align-items: end;
    }

    .add-new-btn {
        padding: 16px;
        background: rgba(139, 92, 246, 0.3);
        border: 1px dashed var(--primary-light);
        border-radius: 14px;
        cursor: pointer;
        width: 60px;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: .3s;
    }

    .add-new-btn:hover {
        background: rgba(139, 92, 246, 0.5);
        transform: scale(1.1);
    }

    .checkbox-group {
        margin-top: 10px;
        display: flex;
        align-items: center;
        gap: 10px;
        font-size: 0.95rem;
    }

    .submit-btn {
        width: 100%;
        padding: 18px;
        margin-top: 50px;
        background: linear-gradient(135deg, var(--primary), var(--primary-light));
        color: white;
        border: none;
        border-radius: 14px;
        font-size: 1.2rem;
        font-weight: 700;
        cursor: pointer;
        box-shadow: 0 10px 30px rgba(139, 92, 246, 0.4);
        transition: .4s;
    }

    .submit-btn:hover {
        transform: translateY(-5px);
        box-shadow: 0 20px 40px rgba(139, 92, 246, 0.5);
    }

    .modal {
        display: none;
        position: fixed;
        inset: 0;
        background: rgba(0, 0, 0, 0.8);
        backdrop-filter: blur(10px);
        align-items: center;
        justify-content: center;
        z-index: 1000;
    }

    .modal.active {
        display: flex;
    }

    .modal-content {
        background: rgba(255, 255, 255, 0.15);
        backdrop-filter: blur(16px);
        border-radius: 20px;
        border: 1px solid rgba(255, 255, 255, 0.3);
        width: 90%;
        max-width: 500px;
        padding: 30px;
    }

    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px solid rgba(255, 255, 255, 0.2);
    }

    .close-modal {
        background: none;
        border: none;
        font-size: 30px;
        color: white;
        cursor: pointer;
    }

    @media (max-width:768px) {
        .form-grid {
            grid-template-columns: 1fr;
        }

        .add-new-group {
            flex-direction: column;
        }

        .add-new-btn {
            width: 100%;
        }
    }
    </style>
</head>

<body>
    <div class="container">
        <div class="header">
            <a href="employee-management.php" class="back-btn"><i class="fas fa-arrow-left"></i> Back</a>
            <h1>Edit Employee</h1>
            <p>Updating details for <strong><?= htmlspecialchars($emp['full_name']) ?>
                    (<?= htmlspecialchars($emp['employee_id']) ?>)</strong></p>
        </div>

        <div class="form-area">
            <?php if ($success): ?>
            <div class="message success"><i class="fas fa-check-circle"></i> <?= $success ?></div>
            <?php endif; ?>
            <?php if ($error): ?>
            <div class="message error"><i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($error) ?></div>
            <?php endif; ?>

            <form action="" method="post" enctype="multipart/form-data" id="employeeForm">
                <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">

                <?php foreach ($sections as $sectionName => $fields): ?>
                <h2 class="section-title"><?= htmlspecialchars($sectionName) ?></h2>
                <div class="form-grid">
                    <?php foreach ($fields as $label => $config): ?>
                    <?php
                            $name = $config['name'];
                            $value = $emp[$name] ?? ($config['value'] ?? '');
                            $required = !empty($config['required']) ? 'required' : '';
                            $readonly = !empty($config['readonly']) ? 'readonly' : '';
                            ?>
                    <div class="form-group">
                        <label><?= htmlspecialchars($label) ?> <?php if ($required): ?><span
                                class="required">*</span><?php endif; ?></label>

                        <?php if ($config['type'] === 'select_plus'): ?>
                        <div class="add-new-group">
                            <select name="<?= $name ?>" <?= $required ?> style="flex:1;" id="select_<?= $name ?>">
                                <option value="">— Select <?= strtolower($label) ?> —</option>
                                <?php
                                            $result = $conn->query($config['options_query']);
                                            while ($row = $result->fetch_assoc()):
                                                $selected = ($row['value'] == $value) ? 'selected' : '';
                                            ?>
                                <option value="<?= htmlspecialchars($row['value']) ?>" <?= $selected ?>>
                                    <?= htmlspecialchars($row['label']) ?>
                                </option>
                                <?php endwhile; ?>
                            </select>
                            <button type="button" class="add-new-btn" onclick="openModal('<?= $config['add_new'] ?>')">
                                <i class="fas fa-plus"></i>
                            </button>
                        </div>

                        <?php elseif ($config['type'] === 'textarea'): ?>
                        <textarea name="<?= $name ?>" <?= $required ?>
                            <?= $readonly ?>><?= htmlspecialchars($value) ?></textarea>

                        <?php elseif ($config['type'] === 'select'): ?>
                        <select name="<?= $name ?>" <?= $required ?>>
                            <?php foreach ($config['options'] as $opt): ?>
                            <option value="<?= htmlspecialchars($opt) ?>" <?= $opt == $value ? 'selected' : '' ?>>
                                <?= $opt ?: '— Select —' ?></option>
                            <?php endforeach; ?>
                        </select>

                        <?php elseif ($config['type'] === 'file'): ?>
                        <input type="file" name="<?= $name ?>" accept="<?= $config['accept'] ?? '*/*' ?>">
                        <?php if ($value): ?>
                        <small style="display:block; margin-top:8px; opacity:0.8;">
                            Current: <a href="../<?= htmlspecialchars($value) ?>" target="_blank">View file</a>
                        </small>
                        <?php endif; ?>

                        <?php else: ?>
                        <input type="<?= $config['type'] ?>" name="<?= $name ?>" value="<?= htmlspecialchars($value) ?>"
                            <?= $required ?> <?= $readonly ?>
                            <?= !empty($config['onchange']) ? 'onchange="' . $config['onchange'] . '"' : '' ?>
                            <?= !empty($config['min']) ? 'min="' . $config['min'] . '"' : '' ?>
                            <?= !empty($config['step']) ? 'step="' . $config['step'] . '"' : '' ?>
                            placeholder="Enter <?= strtolower($label) ?>">
                        <?php endif; ?>

                        <?php if ($label === "Permanent Address"): ?>
                        <div class="checkbox-group">
                            <input type="checkbox" id="copy_address" onchange="copyAddress()">
                            <label for="copy_address">Same as Permanent Address</label>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endforeach; ?>

                <button type="submit" class="submit-btn">
                    <i class="fas fa-save"></i> Update Employee
                </button>
            </form>
        </div>
    </div>

    <!-- Modals -->
    <div id="modal-designation" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Add New Designation</h3>
                <button type="button" class="close-modal" onclick="closeModal('designation')">&times;</button>
            </div>
            <input type="text" id="new_designation" placeholder="Enter designation name"
                style="width:100%; padding:16px; margin-bottom:20px; border-radius:14px; border:1px solid rgba(255,255,255,0.3); background:rgba(255,255,255,0.15); color:white;">
            <button onclick="addNewOption('designation')"
                style="width:100%; padding:16px; background:var(--primary); border:none; border-radius:14px; color:white; font-size:1.1rem; cursor:pointer;">Add
                Designation</button>
        </div>
    </div>

    <div id="modal-education" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Add New Education</h3>
                <button type="button" class="close-modal" onclick="closeModal('education')">&times;</button>
            </div>
            <input type="text" id="new_education" placeholder="Enter education (e.g., B.Tech)"
                style="width:100%; padding:16px; margin-bottom:20px; border-radius:14px; border:1px solid rgba(255,255,255,0.3); background:rgba(255,255,255,0.15); color:white;">
            <button onclick="addNewOption('education')"
                style="width:100%; padding:16px; background:var(--primary); border:none; border-radius:14px; color:white; font-size:1.1rem; cursor:pointer;">Add
                Education</button>
        </div>
    </div>

    <script>
    // Auto Full Name
    document.querySelectorAll('[name="first_name"], [name="middle_name"], [name="last_name"]').forEach(el =>
        el.addEventListener('input', () => {
            const first = document.querySelector('[name="first_name"]').value.trim();
            const middle = document.querySelector('[name="middle_name"]').value.trim();
            const last = document.querySelector('[name="last_name"]').value.trim();
            document.querySelector('[name="full_name"]').value = [first, middle, last].filter(Boolean).join(
            ' ');
        })
    );

    // Calculate Age
    window.calculateAge = function(dob) {
        if (!dob) return;
        const birth = new Date(dob);
        const today = new Date();
        let age = today.getFullYear() - birth.getFullYear();
        const m = today.getMonth() - birth.getMonth();
        if (m < 0 || (m === 0 && today.getDate() < birth.getDate())) age--;
        document.querySelector('[name="age"]').value = age >= 0 ? age : '';
    };

    // Copy Address
    window.copyAddress = function() {
        if (!document.getElementById('copy_address').checked) return;
        const map = {
            permanent_address: 'current_address',
            post: 'current_post',
            city_or_village: 'current_city_or_village',
            state: 'current_state',
            pincode: 'current_pincode'
        };
        Object.keys(map).forEach(src => {
            const srcEl = document.querySelector(`[name="${src}"]`);
            const destEl = document.querySelector(`[name="${map[src]}"]`);
            if (srcEl && destEl) destEl.value = srcEl.value;
        });
    };

    // Aadhar & PAN formatting
    document.querySelector('[name="aadhar_number"]')?.addEventListener('input', e => {
        let v = e.target.value.replace(/\D/g, '').slice(0, 12);
        e.target.value = v.replace(/(\d{4})(?=\d)/g, '$1 ');
    });
    document.querySelector('[name="pan_number"]')?.addEventListener('input', e => {
        e.target.value = e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 10);
    });

    // Modal Functions
    function openModal(type) {
        document.getElementById(`modal-${type}`).classList.add('active');
        document.getElementById(`new_${type}`).focus();
    }

    function closeModal(type) {
        document.getElementById(`modal-${type}`).classList.remove('active');
        document.getElementById(`new_${type}`).value = '';
    }

    async function addNewOption(type) {
        const input = document.getElementById(`new_${type}`);
        const name = input.value.trim();
        if (!name) return alert('Please enter a name');

        const formData = new FormData();
        formData.append('action', `add_${type}`);
        formData.append('name', name);
        formData.append('csrf_token', '<?= $_SESSION['csrf_token'] ?>');

        try {
            const res = await fetch('', {
                method: 'POST',
                body: formData
            });
            const json = await res.json();
            if (json.success) {
                const select = document.getElementById(`select_${type}`);
                const option = new Option(json.value, json.value, true, true);
                select.appendChild(option);
                closeModal(type);
                input.value = '';
            } else {
                alert(json.message);
            }
        } catch (err) {
            alert('Error: Could not add item');
        }
    }
    </script>
</body>

</html>