<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 0); // Disable in production
ini_set('log_errors', 1);
ini_set('error_log', 'error_log.txt');

// Start output buffering and session
ob_start();
session_start();

// Check if user is logged in and has admin privileges
if (!isset($_SESSION['user_id'], $_SESSION['role'], $_SESSION['session_token'])) {
    header('Location: login.php');
    exit();
}

if (!in_array(strtolower($_SESSION['role']), ['superadmin', 'admin'])) {
    header('Location: unauthorized.php');
    exit();
}

// Include database configuration
require_once 'config.php';

// Initialize message
$message = '';

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

// Validate user ID from query parameter
$user_id = isset($_GET['id']) ? trim($_GET['id']) : '';
if (empty($user_id) || !ctype_digit($user_id)) {
    $_SESSION['error_message'] = 'Invalid user ID provided.';
    error_log("Invalid user ID: '$user_id' from " . $_SERVER['REQUEST_URI'] . ", Referer: " . ($_SERVER['HTTP_REFERER'] ?? 'None'));
    header('Location: manage_users.php');
    exit();
}

try {
    // Fetch user details
    $stmt = $conn->prepare('SELECT * FROM users WHERE id = ?');
    if (!$stmt) {
        throw new Exception('Database error: Unable to prepare SELECT statement');
    }
    $stmt->bind_param('i', (int)$user_id);
    if (!$stmt->execute()) {
        throw new Exception('Database error: Unable to execute SELECT query');
    }
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();
    error_log("User query for ID $user_id: " . ($user ? 'Found' : 'Not found'));
    $stmt->close();

    if (!$user) {
        $message = '<div class="alert alert-danger">No user found with ID: ' . htmlspecialchars($user_id, ENT_QUOTES, 'UTF-8') . '</div>';
    }
} catch (Exception $e) {
    $message = '<div class="alert alert-danger">' . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8') . '</div>';
    error_log("Error fetching user ID $user_id: " . $e->getMessage());
    $user = null;
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_user'])) {
    // Validate CSRF token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $message = '<div class="alert alert-danger">CSRF token validation failed.</div>';
        error_log("CSRF token validation failed for user ID $user_id");
    } else {
        try {
            // Sanitize and validate input data
            $fields = [
                'username', 'role', 'status', 'mobileno', 'address', 'responsibilities', 'designation',
                'department', 'marital_status', 'gender', 'mother_name', 'father_name', 'spouse_name',
                'qualification', 'previous_experience', 'company_name', 'last_company_1', 'last_company_2',
                'last_company_3', 'uan_no', 'bloodgroup', 'esic_no', 'bank_name', 'account_number',
                'ifsc_code', 'first_name', 'last_name', 'level', 'position', 'appointment_type',
                'location', 'reporting_manager', 'pancard', 'aadharcard'
            ];
            $data = [];
            foreach ($fields as $field) {
                $data[$field] = isset($_POST[$field]) ? $conn->real_escape_string(trim($_POST[$field])) : '';
            }

            // Nullable date fields
            $date_fields = ['date_of_birth', 'resignation_date', 'rejoin_date'];
            foreach ($date_fields as $field) {
                $data[$field] = !empty($_POST[$field]) ? $conn->real_escape_string(trim($_POST[$field])) : null;
            }

            // Numeric fields
            $data['no_of_children'] = isset($_POST['no_of_children']) ? (int)$_POST['no_of_children'] : 0;
            $data['basic_salary'] = isset($_POST['basic_salary']) ? (float)$_POST['basic_salary'] : 0.0;
            $data['last_company_1_years'] = isset($_POST['last_company_1_years']) ? (int)$_POST['last_company_1_years'] : 0;
            $data['last_company_1_salary'] = isset($_POST['last_company_1_salary']) ? (float)$_POST['last_company_1_salary'] : 0.0;
            $data['last_company_2_years'] = isset($_POST['last_company_2_years']) ? (int)$_POST['last_company_2_years'] : 0;
            $data['last_company_2_salary'] = isset($_POST['last_company_2_salary']) ? (float)$_POST['last_company_2_salary'] : 0.0;
            $data['last_company_3_years'] = isset($_POST['last_company_3_years']) ? (int)$_POST['last_company_3_years'] : 0;
            $data['last_company_3_salary'] = isset($_POST['last_company_3_salary']) ? (float)$_POST['last_company_3_salary'] : 0.0;
            $data['total_experience_years'] = isset($_POST['total_experience_years']) ? (int)$_POST['total_experience_years'] : 0;
            $data['previous_salary'] = isset($_POST['previous_salary']) ? (float)$_POST['previous_salary'] : 0.0;
            $data['performance'] = isset($_POST['performance']) ? (int)$_POST['performance'] : 0;
            $data['role_id'] = isset($_POST['role_id']) ? (int)$_POST['role_id'] : 0;

            // Validate critical fields
            if (empty($user_id) || !ctype_digit($user_id)) {
                throw new Exception('Invalid user ID');
            }

            // Handle file upload
            $photo_path = $user['photo'] ?? 'default-photo.png';
            if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
                $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
                $max_size = 5 * 1024 * 1024; // 5MB
                if (!in_array($_FILES['photo']['type'], $allowed_types) || $_FILES['photo']['size'] > $max_size) {
                    throw new Exception('Invalid file type or size');
                }
                $upload_dir = 'Uploads/';
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0755, true);
                }
                $photo_name = uniqid() . '_' . basename($_FILES['photo']['name']);
                $upload_file = $upload_dir . $photo_name;
                if (!move_uploaded_file($_FILES['photo']['tmp_name'], $upload_file)) {
                    throw new Exception('Failed to upload photo');
                }
                $photo_path = $upload_file;
            }

            // Prepare and execute update query
            $query = "UPDATE users SET
                username=?, role=?, status=?, mobileno=?, address=?, basic_salary=?, responsibilities=?,
                designation=?, department=?, marital_status=?, gender=?, date_of_birth=?,
                mother_name=?, father_name=?, spouse_name=?, no_of_children=?, qualification=?,
                previous_experience=?, company_name=?, last_company_1=?, last_company_1_years=?,
                last_company_1_salary=?, last_company_2=?, last_company_2_years=?,
                last_company_2_salary=?, last_company_3=?, last_company_3_years=?,
                last_company_3_salary=?, total_experience_years=?, previous_salary=?,
                uan_no=?, bloodgroup=?, esic_no=?, bank_name=?, account_number=?,
                ifsc_code=?, first_name=?, last_name=?, level=?, performance=?,
                position=?, appointment_type=?, location=?, resignation_date=?,
                rejoin_date=?, reporting_manager=?, role_id=?, pancard=?, aadharcard=?,
                photo=?
                WHERE id=?";
            $stmt = $conn->prepare($query);
            if (!$stmt) {
                throw new Exception('Error preparing update query: ' . $conn->error);
            }

            // Handle nullable date fields
            $date_of_birth = $data['date_of_birth'] ?? null;
            $resignation_date = $data['resignation_date'] ?? null;
            $rejoin_date = $data['rejoin_date'] ?? null;

            $stmt->bind_param(
                'sssssdsdsssssssssssidddsssiidsssssssssdsissssssisssi',
                $data['username'], $data['role'], $data['status'], $data['mobileno'], $data['address'],
                $data['basic_salary'], $data['responsibilities'], $data['designation'], $data['department'],
                $data['marital_status'], $data['gender'], $date_of_birth, $data['mother_name'],
                $data['father_name'], $data['spouse_name'], $data['no_of_children'], $data['qualification'],
                $data['previous_experience'], $data['company_name'], $data['last_company_1'],
                $data['last_company_1_years'], $data['last_company_1_salary'], $data['last_company_2'],
                $data['last_company_2_years'], $data['last_company_2_salary'], $data['last_company_3'],
                $data['last_company_3_years'], $data['last_company_3_salary'], $data['total_experience_years'],
                $data['previous_salary'], $data['uan_no'], $data['bloodgroup'], $data['esic_no'],
                $data['bank_name'], $data['account_number'], $data['ifsc_code'], $data['first_name'],
                $data['last_name'], $data['level'], $data['performance'], $data['position'],
                $data['appointment_type'], $data['location'], $resignation_date,
                $rejoin_date, $data['reporting_manager'], $data['role_id'], $data['pancard'], $data['aadharcard'],
                $photo_path, (int)$user_id
            );

            if ($stmt->execute()) {
                $message = '<div class="alert alert-success">User updated successfully!</div>';
                error_log("User ID $user_id updated successfully");
                // Refresh user data
                $stmt->close();
                $stmt = $conn->prepare('SELECT * FROM users WHERE id = ?');
                $stmt->bind_param('i', (int)$user_id);
                $stmt->execute();
                $result = $stmt->get_result();
                $user = $result->fetch_assoc();
                $stmt->close();
            } else {
                throw new Exception('Error updating user: ' . $stmt->error);
            }
        } catch (Exception $e) {
            if (isset($stmt) && $stmt instanceof mysqli_stmt) {
                $stmt->close();
            }
            $message = '<div class="alert alert-danger">' . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8') . '</div>';
            error_log("Error updating user ID $user_id: " . $e->getMessage());
        }
    }
}

// Base URL for images
$base_url = 'https://techknow.mybelief.net/';

// End output buffering
ob_end_flush();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit User Details</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background-color: #f8f9fa;
            display: block;
            margin: 0;
            min-height: 100vh;
        }
        .sidebar {
            width: 250px;
            background-color: #343a40;
            color: #fff;
            padding: 20px;
            position: fixed;
            height: 100%;
            transform: translateX(-250px);
            transition: transform 0.3s ease;
            z-index: 1000;
        }
        .sidebar.active {
            transform: translateX(0);
        }
        .sidebar h2 {
            font-size: 1.2rem;
            margin-bottom: 20px;
        }
        .sidebar a {
            color: #fff;
            text-decoration: none;
            padding: 10px;
            display: block;
            border-radius: 5px;
            margin-bottom: 5px;
        }
        .sidebar a:hover {
            background-color: #495057;
        }
        .hamburger {
            position: fixed;
            top: 15px;
            left: 15px;
            z-index: 1100;
            background-color: #343a40;
            color: #fff;
            border: none;
            padding: 10px;
            border-radius: 5px;
            cursor: pointer;
        }
        .content {
            margin-left: 0;
            padding: 20px;
            transition: margin-left 0.3s ease;
        }
        .content.active {
            margin-left: 250px;
        }
        .card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        .user-photo {
            width: 100px;
            height: 100px;
            object-fit: cover;
            border-radius: 5px;
            margin-bottom: 10px;
        }
        .btn-spacing {
            margin-right: 10px;
        }
        @media (max-width: 576px) {
            .content {
                padding: 15px;
            }
            .card {
                padding: 15px;
            }
        }
    </style>
</head>
<body>
    <button class="hamburger" onclick="toggleSidebar()">
        <i class="fas fa-bars"></i>
    </button>

    <div class="sidebar" id="sidebar">
        <h2>Techknow</h2>
        <a href="dashboard_admin.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
        <a href="manage_users.php"><i class="fas fa-users"></i> Manage Users</a>
        <a href="manage_documents.php"><i class="fas fa-folder"></i> Manage Documents</a>
        <a href="grievance_users.php"><i class="fas fa-balance-scale"></i> Grievance Users</a>
        <a href="leave_users.php"><i class="fas fa-umbrella"></i> Leave Users</a>
        <a href="dashboard_user.php"><i class="fas fa-user"></i> Personal User</a>
        <a href="logout.php" class="text-danger"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </div>

    <div class="content" id="content">
        <h1 class="text-primary text-center mb-4">Edit User Details</h1>
        <div class="container">
            <?php echo $message; ?>
            <?php if ($user) { ?>
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="id" value="<?php echo htmlspecialchars($user['id'], ENT_QUOTES, 'UTF-8'); ?>">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8'); ?>">

                    <!-- Personal Details -->
                    <div class="card">
                        <h3 class="mb-3">Personal Details</h3>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="first_name" class="form-label">First Name</label>
                                <input type="text" class="form-control" id="first_name" name="first_name" value="<?php echo htmlspecialchars($user['first_name'], ENT_QUOTES, 'UTF-8'); ?>" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="last_name" class="form-label">Last Name</label>
                                <input type="text" class="form-control" id="last_name" name="last_name" value="<?php echo htmlspecialchars($user['last_name'], ENT_QUOTES, 'UTF-8'); ?>" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="gender" class="form-label">Gender</label>
                                <select class="form-select" id="gender" name="gender" required>
                                    <option value="Male" <?php echo ($user['gender'] === 'Male') ? 'selected' : ''; ?>>Male</option>
                                    <option value="Female" <?php echo ($user['gender'] === 'Female') ? 'selected' : ''; ?>>Female</option>
                                    <option value="Others" <?php echo ($user['gender'] === 'Others') ? 'selected' : ''; ?>>Others</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="date_of_birth" class="form-label">Date of Birth</label>
                                <input type="date" class="form-control" id="date_of_birth" name="date_of_birth" value="<?php echo htmlspecialchars($user['date_of_birth'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="marital_status" class="form-label">Marital Status</label>
                                <select class="form-select" id="marital_status" name="marital_status" required>
                                    <option value="Single" <?php echo ($user['marital_status'] === 'Single') ? 'selected' : ''; ?>>Single</option>
                                    <option value="Married" <?php echo ($user['marital_status'] === 'Married') ? 'selected' : ''; ?>>Married</option>
                                    <option value="Divorced" <?php echo ($user['marital_status'] === 'Divorced') ? 'selected' : ''; ?>>Divorced</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="spouse_name" class="form-label">Spouse Name</label>
                                <input type="text" class="form-control" id="spouse_name" name="spouse_name" value="<?php echo htmlspecialchars($user['spouse_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="no_of_children" class="form-label">Number of Children</label>
                                <input type="number" class="form-control" id="no_of_children" name="no_of_children" value="<?php echo htmlspecialchars($user['no_of_children'] ?? 0, ENT_QUOTES, 'UTF-8'); ?>" min="0">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="mother_name" class="form-label">Mother's Name</label>
                                <input type="text" class="form-control" id="mother_name" name="mother_name" value="<?php echo htmlspecialchars($user['mother_name'], ENT_QUOTES, 'UTF-8'); ?>" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="father_name" class="form-label">Father's Name</label>
                                <input type="text" class="form-control" id="father_name" name="father_name" value="<?php echo htmlspecialchars($user['father_name'], ENT_QUOTES, 'UTF-8'); ?>" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="bloodgroup" class="form-label">Blood Group</label>
                                <input type="text" class="form-control" id="bloodgroup" name="bloodgroup" value="<?php echo htmlspecialchars($user['bloodgroup'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                            </div>
                        </div>
                    </div>

                    <!-- Contact Details -->
                    <div class="card">
                        <h3 class="mb-3">Contact Details</h3>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="username" class="form-label">Username</label>
                                <input type="text" class="form-control" id="username" name="username" value="<?php echo htmlspecialchars($user['username'], ENT_QUOTES, 'UTF-8'); ?>" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="mobileno" class="form-label">Mobile Number</label>
                                <input type="text" class="form-control" id="mobileno" name="mobileno" value="<?php echo htmlspecialchars($user['mobileno'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="address" class="form-label">Address</label>
                                <textarea class="form-control" id="address" name="address"><?php echo htmlspecialchars($user['address'] ?? '', ENT_QUOTES, 'UTF-8'); ?></textarea>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="pancard" class="form-label">PAN Card</label>
                                <input type="text" class="form-control" id="pancard" name="pancard" value="<?php echo htmlspecialchars($user['pancard'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="aadharcard" class="form-label">Aadhar Card</label>
                                <input type="text" class="form-control" id="aadharcard" name="aadharcard" value="<?php echo htmlspecialchars($user['aadharcard'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                            </div>
                            <div class="col-md-12 mb-3">
                                <label for="photo" class="form-label">Photo</label><br>
                                <?php
                                $photo_path = !empty($user['photo']) ? $user['photo'] : 'default-photo.png';
                                $full_path = $_SERVER['DOCUMENT_ROOT'] . '/' . $photo_path;
                                $url_path = $base_url . $photo_path . '?cb=' . time();
                                if ($photo_path !== 'default-photo.png' && file_exists($full_path)) {
                                    echo '<img src="' . htmlspecialchars($url_path, ENT_QUOTES, 'UTF-8') . '" class="user-photo" alt="User Photo">';
                                } else {
                                    echo '<img src="' . htmlspecialchars($base_url . 'default-photo.png?cb=' . time(), ENT_QUOTES, 'UTF-8') . '" class="user-photo" alt="Default Photo">';
                                }
                                ?>
                                <input type="file" class="form-control mt-2" id="photo" name="photo" accept="image/*">
                            </div>
                        </div>
                    </div>

                    <!-- Employment Details -->
                    <div class="card">
                        <h3 class="mb-3">Employment Details</h3>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="role" class="form-label">Role</label>
                                <select class="form-select" id="role" name="role" required>
                                    <option value="superadmin" <?php echo ($user['role'] === 'superadmin') ? 'selected' : ''; ?>>Superadmin</option>
                                    <option value="admin" <?php echo ($user['role'] === 'admin') ? 'selected' : ''; ?>>Admin</option>
                                    <option value="employee" <?php echo ($user['role'] === 'employee') ? 'selected' : ''; ?>>Employee</option>
                                    <option value="manager" <?php echo ($user['role'] === 'manager') ? 'selected' : ''; ?>>Manager</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="designation" class="form-label">Designation</label>
                                <select class="form-select" id="designation" name="designation" required>
                                    <option value="TRAINEE TECHNICIAN" <?php echo ($user['designation'] === 'TRAINEE TECHNICIAN') ? 'selected' : ''; ?>>Trainee Technician</option>
                                    <option value="TERRITORY MANAGER" <?php echo ($user['designation'] === 'TERRITORY MANAGER') ? 'selected' : ''; ?>>Territory Manager</option>
                                    <option value="SERVICE ENGINEER" <?php echo ($user['designation'] === 'SERVICE ENGINEER') ? 'selected' : ''; ?>>Service Engineer</option>
                                    <option value="Executive" <?php echo ($user['designation'] === 'Executive') ? 'selected' : ''; ?>>Executive</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="department" class="form-label">Department</label>
                                <select class="form-select" id="department" name="department" required>
                                    <option value="STORES" <?php echo ($user['department'] === 'STORES') ? 'selected' : ''; ?>>Stores</option>
                                    <option value="SERVICE" <?php echo ($user['department'] === 'SERVICE') ? 'selected' : ''; ?>>Service</option>
                                    <option value="SALES(VFD)" <?php echo ($user['department'] === 'SALES(VFD)') ? 'selected' : ''; ?>>Sales (VFD)</option>
                                    <option value="SALES & SERVICE" <?php echo ($user['department'] === 'SALES & SERVICE') ? 'selected' : ''; ?>>Sales & Service</option>
                                    <option value="IT" <?php echo ($user['department'] === 'IT') ? 'selected' : ''; ?>>IT</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="level" class="form-label">Level</label>
                                <select class="form-select" id="level" name="level" required>
                                    <option value="L1" <?php echo ($user['level'] === 'L1') ? 'selected' : ''; ?>>L1</option>
                                    <option value="L2" <?php echo ($user['level'] === 'L2') ? 'selected' : ''; ?>>L2</option>
                                    <option value="L3" <?php echo ($user['level'] === 'L3') ? 'selected' : ''; ?>>L3</option>
                                    <option value="L4" <?php echo ($user['level'] === 'L4') ? 'selected' : ''; ?>>L4</option>
                                    <option value="L5" <?php echo ($user['level'] === 'L5') ? 'selected' : ''; ?>>L5</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="position" class="form-label">Position</label>
                                <input type="text" class="form-control" id="position" name="position" value="<?php echo htmlspecialchars($user['position'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="appointment_type" class="form-label">Appointment Type</label>
                                <select class="form-select" id="appointment_type" name="appointment_type" required>
                                    <option value="regular" <?php echo ($user['appointment_type'] === 'regular') ? 'selected' : ''; ?>>Regular</option>
                                    <option value="contract" <?php echo ($user['appointment_type'] === 'contract') ? 'selected' : ''; ?>>Contract</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="location" class="form-label">Location</label>
                                <select class="form-select" id="location" name="location" required>
                                    <option value="chennai" <?php echo ($user['location'] === 'chennai') ? 'selected' : ''; ?>>Chennai</option>
                                    <option value="coimbatore" <?php echo ($user['location'] === 'coimbatore') ? 'selected' : ''; ?>>Coimbatore</option>
                                    <option value="madurai" <?php echo ($user['location'] === 'madurai') ? 'selected' : ''; ?>>Madurai</option>
                                    <option value="bengaluru" <?php echo ($user['location'] === 'bengaluru') ? 'selected' : ''; ?>>Bengaluru</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="reporting_manager" class="form-label">Reporting Manager</label>
                                <input type="text" class="form-control" id="reporting_manager" name="reporting_manager" value="<?php echo htmlspecialchars($user['reporting_manager'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="responsibilities" class="form-label">Responsibilities</label>
                                <textarea class="form-control" id="responsibilities" name="responsibilities"><?php echo htmlspecialchars($user['responsibilities'] ?? '', ENT_QUOTES, 'UTF-8'); ?></textarea>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="role_id" class="form-label">Role ID</label>
                                <input type="number" class="form-control" id="role_id" name="role_id" value="<?php echo htmlspecialchars($user['role_id'] ?? 0, ENT_QUOTES, 'UTF-8'); ?>" min="0">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="status" class="form-label">Status</label>
                                <select class="form-select" id="status" name="status" required>
                                    <option value="active" <?php echo ($user['status'] === 'active') ? 'selected' : ''; ?>>Active</option>
                                    <option value="resigned" <?php echo ($user['status'] === 'resigned') ? 'selected' : ''; ?>>Resigned</option>
                                    <option value="deleted" <?php echo ($user['status'] === 'deleted') ? 'selected' : ''; ?>>Deleted</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="performance" class="form-label">Performance</label>
                                <input type="number" class="form-control" id="performance" name="performance" value="<?php echo htmlspecialchars($user['performance'] ?? 0, ENT_QUOTES, 'UTF-8'); ?>" min="0">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="resignation_date" class="form-label">Resignation Date</label>
                                <input type="date" class="form-control" id="resignation_date" name="resignation_date" value="<?php echo htmlspecialchars($user['resignation_date'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="rejoin_date" class="form-label">Rejoin Date</label>
                                <input type="date" class="form-control" id="rejoin_date" name="rejoin_date" value="<?php echo htmlspecialchars($user['rejoin_date'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                            </div>
                        </div>
                    </div>

                    <!-- Financial Details -->
                    <div class="card">
                        <h3 class="mb-3">Financial Details</h3>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="basic_salary" class="form-label">Basic Salary</label>
                                <input type="number" step="0.01" class="form-control" id="basic_salary" name="basic_salary" value="<?php echo htmlspecialchars($user['basic_salary'] ?? 0, ENT_QUOTES, 'UTF-8'); ?>" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="bank_name" class="form-label">Bank Name</label>
                                <input type="text" class="form-control" id="bank_name" name="bank_name" value="<?php echo htmlspecialchars($user['bank_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="account_number" class="form-label">Account Number</label>
                                <input type="text" class="form-control" id="account_number" name="account_number" value="<?php echo htmlspecialchars($user['account_number'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="ifsc_code" class="form-label">IFSC Code</label>
                                <input type="text" class="form-control" id="ifsc_code" name="ifsc_code" value="<?php echo htmlspecialchars($user['ifsc_code'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="uan_no" class="form-label">UAN Number</label>
                                <input type="text" class="form-control" id="uan_no" name="uan_no" value="<?php echo htmlspecialchars($user['uan_no'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="esic_no" class="form-label">ESIC Number</label>
                                <input type="text" class="form-control" id="esic_no" name="esic_no" value="<?php echo htmlspecialchars($user['esic_no'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                            </div>
                        </div>
                    </div>

                    <!-- Experience Details -->
                    <div class="card">
                        <h3 class="mb-3">Experience Details</h3>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="qualification" class="form-label">Qualification</label>
                                <input type="text" class="form-control" id="qualification" name="qualification" value="<?php echo htmlspecialchars($user['qualification'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="previous_experience" class="form-label">Previous Experience</label>
                                <input type="text" class="form-control" id="previous_experience" name="previous_experience" value="<?php echo htmlspecialchars($user['previous_experience'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="company_name" class="form-label">Company Name</label>
                                <input type="text" class="form-control" id="company_name" name="company_name" value="<?php echo htmlspecialchars($user['company_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="total_experience_years" class="form-label">Total Experience (Years)</label>
                                <input type="number" class="form-control" id="total_experience_years" name="total_experience_years" value="<?php echo htmlspecialchars($user['total_experience_years'] ?? 0, ENT_QUOTES, 'UTF-8'); ?>" min="0">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="last_company_1" class="form-label">Last Company 1</label>
                                <input type="text" class="form-control" id="last_company_1" name="last_company_1" value="<?php echo htmlspecialchars($user['last_company_1'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="last_company_1_years" class="form-label">Years</label>
                                <input type="number" class="form-control" id="last_company_1_years" name="last_company_1_years" value="<?php echo htmlspecialchars($user['last_company_1_years'] ?? 0, ENT_QUOTES, 'UTF-8'); ?>" min="0">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="last_company_1_salary" class="form-label">Salary</label>
                                <input type="number" step="0.01" class="form-control" id="last_company_1_salary" name="last_company_1_salary" value="<?php echo htmlspecialchars($user['last_company_1_salary'] ?? 0, ENT_QUOTES, 'UTF-8'); ?>">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="last_company_2" class="form-label">Last Company 2</label>
                                <input type="text" class="form-control" id="last_company_2" name="last_company_2" value="<?php echo htmlspecialchars($user['last_company_2'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="last_company_2_years" class="form-label">Years</label>
                                <input type="number" class="form-control" id="last_company_2_years" name="last_company_2_years" value="<?php echo htmlspecialchars($user['last_company_2_years'] ?? 0, ENT_QUOTES, 'UTF-8'); ?>" min="0">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="last_company_2_salary" class="form-label">Salary</label>
                                <input type="number" step="0.01" class="form-control" id="last_company_2_salary" name="last_company_2_salary" value="<?php echo htmlspecialchars($user['last_company_2_salary'] ?? 0, ENT_QUOTES, 'UTF-8'); ?>">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="last_company_3" class="form-label">Last Company 3</label>
                                <input type="text" class="form-control" id="last_company_3" name="last_company_3" value="<?php echo htmlspecialchars($user['last_company_3'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="last_company_3_years" class="form-label">Years</label>
                                <input type="number" class="form-control" id="last_company_3_years" name="last_company_3_years" value="<?php echo htmlspecialchars($user['last_company_3_years'] ?? 0, ENT_QUOTES, 'UTF-8'); ?>" min="0">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="last_company_3_salary" class="form-label">Salary</label>
                                <input type="number" step="0.01" class="form-control" id="last_company_3_salary" name="last_company_3_salary" value="<?php echo htmlspecialchars($user['last_company_3_salary'] ?? 0, ENT_QUOTES, 'UTF-8'); ?>">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="previous_salary" class="form-label">Previous Salary</label>
                                <input type="number" step="0.01" class="form-control" id="previous_salary" name="previous_salary" value="<?php echo htmlspecialchars($user['previous_salary'] ?? 0, ENT_QUOTES, 'UTF-8'); ?>">
                            </div>
                        </div>
                    </div>

                    <!-- Submit Buttons -->
                    <div class="card">
                        <button type="submit" name="update_user" class="btn btn-primary btn-spacing">Update User</button>
                        <a href="manage_users.php" class="btn btn-secondary btn-spacing">Cancel</a>
                    </div>
                </form>
            <?php } else { ?>
                <div class="card">
                    <p class="mb-3">No user details available.</p>
                    <a href="manage_users.php" class="btn btn-primary btn-spacing">Back to Manage Users</a>
                </div>
            <?php } ?>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
    <script>
        function toggleSidebar() {
            document.getElementById('sidebar').classList.toggle('active');
            document.getElementById('content').classList.toggle('active');
        }

        document.addEventListener('DOMContentLoaded', () => {
            const statusSelect = document.getElementById('status');
            const form = document.querySelector('form');
            if (form && statusSelect) {
                const inputs = form.querySelectorAll('input, select, textarea, button');
                function toggleFormFields() {
                    const isActive = statusSelect.value === 'active';
                    inputs.forEach(input => {
                        if (input.id !== 'status' && input.name !== 'update_user') {
                            input.disabled = !isActive;
                        }
                    });
                }
                toggleFormFields();
                statusSelect.addEventListener('change', toggleFormFields);
            }
        });
    </script>
</body>
</html>