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

// Start session
session_start();

// Include database configuration
if (!file_exists('config.php')) {
    error_log("Config file missing: config.php");
    die("Configuration file not found. Please contact the administrator.");
}
include 'config.php';

// Verify database connection
if ($conn->connect_error) {
    error_log("Database connection failed: " . $conn->connect_error);
    die("Unable to connect to the database. Please contact the administrator.");
}

// Ensure only Employees can access this page
if (!isset($_SESSION['user_id'], $_SESSION['role']) || $_SESSION['role'] !== 'employee') {
    error_log("Unauthorized access attempt. Session data: user_id=" . ($_SESSION['user_id'] ?? 'not set') . ", role=" . ($_SESSION['role'] ?? 'not set'));
    header("Location: index.php");
    exit();
}

$user_id = $_SESSION['user_id']; // Keep as string to match database
$username = $_SESSION['username'] ?? 'Unknown User';
error_log("Personal Info accessed by Employee ID: $user_id, Username: $username");

// Define allowed fields for editing
$allowed_fields = [
    'username', 'email', 'mobileno', 'address', 'pancard', 'aadharcard', 
    'marital_status', 'anniversary_date', 'gender', 'date_of_birth', 
    'mother_name', 'father_name', 'spouse_name', 'no_of_children', 'qualification',
    'previous_experience', 'company_name', 'total_experience_years', 'previous_salary',
    'uan_no', 'bloodgroup', 'esic_no', 'bank_name', 'account_number', 'ifsc_code',
    'first_name', 'last_name'
];

// Handle photo upload
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['profile_photo']) && isset($_POST['user_id'])) {
    $post_user_id = trim($_POST['user_id']);
    if ($post_user_id !== $user_id) {
        error_log("Unauthorized photo update attempt: POST user_id ($post_user_id) does not match session user_id ($user_id)");
        $message = '<div class="alert alert-danger">Unauthorized action: You can only edit your own information.</div>';
    } else {
        $file = $_FILES['profile_photo'];
        if ($file['error'] === 0) {
            $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
            $max_size = 2 * 1024 * 1024; // 2MB
            if (in_array($file['type'], $allowed_types) && $file['size'] <= $max_size) {
                $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
                $new_filename = "user_{$user_id}_" . time() . "." . $ext;
                $base_url = '/demo.mypeopleconnect.app/uploads/';
                $upload_path = $_SERVER['DOCUMENT_ROOT'] . $base_url . $new_filename;
                if (move_uploaded_file($file['tmp_name'], $upload_path)) {
                    // Update database
                    $sql = "UPDATE users SET photo = ? WHERE id = ?";
                    $stmt = $conn->prepare($sql);
                    if ($stmt) {
                        $stmt->bind_param('ss', $new_filename, $user_id);
                        if ($stmt->execute()) {
                            $message = '<div class="alert alert-success">Photo updated successfully!</div>';
                        } else {
                            $message = '<div class="alert alert-danger">Failed to update photo in database.</div>';
                        }
                        $stmt->close();
                    } else {
                        $message = '<div class="alert alert-danger">Database error: Unable to prepare update query.</div>';
                    }
                } else {
                    $message = '<div class="alert alert-danger">Failed to upload photo to server.</div>';
                }
            } else {
                $message = '<div class="alert alert-danger">Invalid file type or size. Only JPG, PNG, GIF up to 2MB allowed.</div>';
            }
        } else {
            $message = '<div class="alert alert-danger">Error uploading file: ' . $file['error'] . '</div>';
        }
    }
    // Redirect to refresh page
    header("Location: personalinfo.php");
    exit();
}

// Handle form submission for field updates
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['field_name'], $_POST['field_value'], $_POST['user_id'])) {
    $field_name = trim($_POST['field_name']);
    $field_value = trim($_POST['field_value']);
    $post_user_id = trim($_POST['user_id']);

    // Verify that the user_id in POST matches the logged-in user's ID
    if ($post_user_id !== $user_id) {
        error_log("Unauthorized update attempt: POST user_id ($post_user_id) does not match session user_id ($user_id)");
        $message = '<div class="alert alert-danger">Unauthorized action: You can only edit your own information.</div>';
    } elseif (!in_array($field_name, $allowed_fields)) {
        error_log("Invalid field name attempted: $field_name");
        $message = '<div class="alert alert-danger">Invalid field name.</div>';
    } else {
        // Validate field value based on column type
        $error = false;
        if ($field_name === 'email' && !empty($field_value) && !filter_var($field_value, FILTER_VALIDATE_EMAIL)) {
            $message = '<div class="alert alert-danger">Invalid email format.</div>';
            $error = true;
        } elseif ($field_name === 'previous_salary' && !empty($field_value) && !is_numeric(str_replace(',', '', $field_value))) {
            $message = '<div class="alert alert-danger">Salary must be a valid number.</div>';
            $error = true;
        } elseif (in_array($field_name, ['anniversary_date', 'date_of_birth']) && !empty($field_value) && !DateTime::createFromFormat('Y-m-d', $field_value)) {
            $message = '<div class="alert alert-danger">Invalid date format (YYYY-MM-DD).</div>';
            $error = true;
        } elseif (in_array($field_name, ['no_of_children', 'total_experience_years']) && !empty($field_value) && !is_numeric($field_value)) {
            $message = '<div class="alert alert-danger">Field must be a number.</div>';
            $error = true;
        }

        if (!$error) {
            // Special handling for specific fields
            if ($field_name === 'previous_salary') {
                $field_value = str_replace(',', '', $field_value);
            } elseif (in_array($field_name, ['anniversary_date', 'date_of_birth'])) {
                $field_value = (empty($field_value) || strtolower($field_value) === 'n/a') ? null : $field_value;
            }

            try {
                $sql = "UPDATE users SET `$field_name` = ? WHERE id = ?";
                $stmt = $conn->prepare($sql);
                if (!$stmt) {
                    error_log("Update query preparation failed: " . $conn->error . " | Query: $sql");
                    $message = '<div class="alert alert-danger">Database error: Unable to prepare update query.</div>';
                } else {
                    $stmt->bind_param('ss', $field_value, $user_id);
                    if ($stmt->execute()) {
                        if ($stmt->affected_rows > 0) {
                            error_log("Field '$field_name' updated successfully for user_id: $user_id, new value: $field_value");
                            $message = '<div class="alert alert-success">Field updated successfully!</div>';
                        } else {
                            error_log("No changes made for field '$field_name' for user_id: $user_id");
                            $message = '<div class="alert alert-info">No changes were made.</div>';
                        }
                    } else {
                        error_log("Update query execution failed: " . $stmt->error . " | Query: $sql");
                        $message = '<div class="alert alert-danger">Error updating field: ' . htmlspecialchars($stmt->error) . '</div>';
                    }
                    $stmt->close();
                }
            } catch (Exception $e) {
                error_log("Exception in update query: " . $e->getMessage() . " | Query: $sql");
                $message = '<div class="alert alert-danger">An error occurred: ' . htmlspecialchars($e->getMessage()) . '</div>';
            }
        }
    }
    // Redirect to refresh page after update
    header("Location: personalinfo.php");
    exit();
}

// Fetch user details with dynamic column checking
$user = [];
$user_error = null;
$required_columns = ['id', 'username', 'email', 'role', 'status'];
$optional_columns = [
    'first_name', 'last_name', 'mobileno', 'department', 'designation', 'position', 
    'date_of_joining', 'resignation_date', 'rejoin_date', 'basic_salary', 'role_id', 
    'address', 'pancard', 'aadharcard', 'photo', 'marital_status', 'anniversary_date', 
    'gender', 'date_of_birth', 'mother_name', 'father_name', 'spouse_name', 
    'no_of_children', 'qualification', 'previous_experience', 'company_name', 
    'total_experience_years', 'previous_salary', 'uan_no', 'bloodgroup', 'esic_no', 
    'bank_name', 'account_number', 'ifsc_code', 'level', 'performance', 
    'appointment_type', 'location', 'reporting_manager', 'responsibilities'
];

// Function to check if a column exists
function columnExists($conn, $table, $column) {
    try {
        $result = $conn->query("SHOW COLUMNS FROM `$table` LIKE '$column'");
        return $result && $result->num_rows > 0;
    } catch (Exception $e) {
        error_log("Column existence check failed for '$table.$column': " . $e->getMessage());
        return false;
    }
}

// Build dynamic query with existing columns
$existing_columns = array_filter(array_merge($required_columns, $optional_columns), function($col) use ($conn) {
    return columnExists($conn, 'users', $col);
});

if (empty($existing_columns)) {
    error_log("No valid columns found in 'users' table for user_id: $user_id");
    $user_error = "No valid columns found in the users table. Please contact the administrator.";
} else {
    $personal_sql = "SELECT " . implode(', ', $existing_columns) . " FROM users WHERE id = ?";
    try {
        $stmt_personal = $conn->prepare($personal_sql);
        if (!$stmt_personal) {
            error_log("User details query preparation failed: " . $conn->error . " | Query: $personal_sql");
            $user_error = "Unable to prepare user details query. Please contact the administrator.";
        } else {
            $stmt_personal->bind_param("s", $user_id);
            if (!$stmt_personal->execute()) {
                error_log("User details query execution failed: " . $stmt_personal->error . " | Query: $personal_sql");
                $user_error = "Unable to fetch your details. Please try again later.";
            } else {
                $result = $stmt_personal->get_result();
                $user = $result->fetch_assoc() ?? [];
                if (empty($user)) {
                    error_log("No user details found for user_id: $user_id");
                    $user_error = "No user details found for your account.";
                }
            }
            $stmt_personal->close();
        }
    } catch (Exception $e) {
        error_log("Exception in user details query: " . $e->getMessage() . " | Query: $personal_sql");
        $user_error = "An error occurred while fetching your details: " . htmlspecialchars($e->getMessage());
    }
}

// Base URL for images
$base_url = '/demo.mypeopleconnect.app/uploads/';
$default_photo = 'default-profile.png';
$photo_url = !empty($user['photo']) ? $base_url . $user['photo'] . '?cb=' . time() : $base_url . $default_photo . '?cb=' . time();
$photo_full_path = $_SERVER['DOCUMENT_ROOT'] . $base_url . (!empty($user['photo']) ? $user['photo'] : $default_photo);

// Verify photo existence
if (!empty($user['photo']) && !file_exists($photo_full_path)) {
    error_log("Photo not found at: $photo_full_path for user_id: $user_id");
    $photo_url = $base_url . $default_photo . '?cb=' . time();
}

// Close database connection
$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Personal Info</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
            display: flex;
            min-height: 100vh;
        }
        .sidebar {
            width: 250px;
            background: #2c3e50;
            color: #fff;
            padding: 15px;
            transition: transform 0.3s ease;
            position: fixed;
            top: 0;
            bottom: 0;
            z-index: 1000;
            transform: translateX(-250px);
        }
        .sidebar.active {
            transform: translateX(0);
        }
        .sidebar h2 {
            font-size: 1rem;
            margin-bottom: 15px;
        }
        .sidebar a {
            color: #fff;
            text-decoration: none;
            padding: 8px 10px;
            display: block;
            border-radius: 4px;
            margin-bottom: 5px;
            font-size: 0.9rem;
        }
        .sidebar a:hover {
            background: #1abc9c;
        }
        .sidebar a.active {
            background: #1abc9c;
        }
        .hamburger {
            position: fixed;
            top: 10px;
            left: 10px;
            z-index: 1100;
            background: #2c3e50;
            color: #fff;
            border: none;
            padding: 8px;
            border-radius: 4px;
            cursor: pointer;
        }
        .content {
            flex: 1;
            padding: 15px;
            margin-left: 0;
            transition: margin-left 0.3s ease;
        }
        .content.active {
            margin-left: 250px;
        }
        h1 {
            font-size: 1.5rem;
            margin-bottom: 15px;
            color: #333;
        }
        h3 {
            font-size: 1.2rem;
            color: #2c3e50;
            margin-top: 20px;
            margin-bottom: 15px;
        }
        .card {
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .table-responsive {
            font-size: 0.85rem;
        }
        .table th, .table td {
            padding: 8px;
            border: 1px solid #ddd;
            vertical-align: middle;
        }
        .table th {
            background: #2c3e50;
            color: white;
        }
        .btn {
            padding: 6px 12px;
            font-size: 0.85rem;
            touch-action: manipulation;
        }
        .profile-photo {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            object-fit: cover;
            border: 3px solid #ddd;
        }
        .edit-icon {
            color: #6c757d;
            cursor: pointer;
            margin-left: 10px;
            transition: all 0.2s;
        }
        .edit-icon:hover {
            color: #3498db;
        }
        .date-cell {
            white-space: nowrap;
        }
        @media (max-width: 576px) {
            .table-responsive {
                font-size: 0.75rem;
            }
            .btn {
                padding: 4px 8px;
                font-size: 0.75rem;
            }
            .card {
                padding: 10px;
            }
            h1 {
                font-size: 1.2rem;
            }
            h3 {
                font-size: 1rem;
            }
        }
    </style>
</head>
<body>
    <!-- Hamburger Menu -->
    <button class="hamburger" onclick="toggleSidebar()">
        <i class="fas fa-bars"></i>
    </button>

    <!-- Sidebar -->
    <div class="sidebar" id="sidebar">
    <h2>MPC</h2>
    <a href="dashboard_employee.php" class="active">Dashboard</a>
    <a href="personalinfo.php">Personal Info</a>
    <a href="employee_grievance.php">Apply Grievance</a>
    <a href="apply_leave.php">Apply Leave</a>
    <a href="expense.php">Apply Expenses</a>
    <a href="logout.php" class="text-danger">Logout</a>
</div>

    <!-- Main Content -->
    <div class="content" id="content">
        <h1 class="text-primary text-center">Personal Information</h1>
        <?php if ($message): ?>
            <?php echo $message; ?>
        <?php endif; ?>
        <div class="card">
            <h3><i class="fas fa-info-circle"></i> My Details</h3>
            <?php if (isset($user_error)): ?>
                <div class="alert alert-danger"><?php echo htmlspecialchars($user_error); ?></div>
            <?php elseif ($user): ?>
                <div class="text-center mb-4">
                    <img src="<?php echo htmlspecialchars($photo_url); ?>" onerror="this.src='<?php echo htmlspecialchars($base_url . $default_photo . '?cb=' . time()); ?>'" class="profile-photo mb-3" alt="Profile Photo">
                    <br>
                    <button class="btn btn-primary btn-sm" onclick="openPhotoModal('<?php echo htmlspecialchars($user['id']); ?>')">Change Photo</button>
                </div>
                <div class="table-responsive">
                    <table class="table table-bordered">
                        <tbody>
                            <?php
                            $display_fields = [
                                'id' => 'Employee ID',
                                'username' => 'Username',
                                'first_name' => 'First Name',
                                'last_name' => 'Last Name',
                                'email' => 'Email',
                                'mobileno' => 'Mobile Number',
                                'role' => 'Role',
                                'status' => 'Status',
                                'reporting_manager' => 'Reporting Manager',
                                'department' => 'Department',
                                'designation' => 'Designation',
                                'position' => 'Position',
                                'level' => 'Level',
                                'appointment_type' => 'Appointment Type',
                                'location' => 'Location',
                                'basic_salary' => 'Basic Salary',
                                'responsibilities' => 'Responsibilities',
                                'role_id' => 'Role ID',
                                'address' => 'Address',
                                'pancard' => 'PAN Card',
                                'aadharcard' => 'Aadhar Card',
                                'marital_status' => 'Marital Status',
                                'anniversary_date' => 'Anniversary Date',
                                'gender' => 'Gender',
                                'date_of_birth' => 'Date of Birth',
                                'date_of_joining' => 'Date of Joining',
                                'resignation_date' => 'Resignation Date',
                                'rejoin_date' => 'Rejoin Date',
                                'mother_name' => 'Mother\'s Name',
                                'father_name' => 'Father\'s Name',
                                'spouse_name' => 'Spouse Name',
                                'no_of_children' => 'No. of Children',
                                'qualification' => 'Qualification',
                                'previous_experience' => 'Previous Experience',
                                'company_name' => 'Previous Company',
                                'total_experience_years' => 'Total Experience (Years)',
                                'previous_salary' => 'Previous Salary',
                                'uan_no' => 'UAN No.',
                                'bloodgroup' => 'Blood Group',
                                'esic_no' => 'ESIC No.',
                                'bank_name' => 'Bank Name',
                                'account_number' => 'Account Number',
                                'ifsc_code' => 'IFSC Code',
                                'performance' => 'Performance'
                            ];

                            foreach ($display_fields as $field => $label) {
                                if (in_array($field, $existing_columns)) {
                                    echo '<tr>';
                                    echo '<th>' . htmlspecialchars($label) . '</th>';
                                    echo '<td>';
                                    if (in_array($field, ['date_of_birth', 'date_of_joining', 'resignation_date', 'rejoin_date', 'anniversary_date']) && !empty($user[$field])) {
                                        echo htmlspecialchars(date("M d, Y", strtotime($user[$field])));
                                    } elseif ($field === 'responsibilities' || $field === 'address') {
                                        echo nl2br(htmlspecialchars($user[$field] ?? 'N/A'));
                                    } else {
                                        echo htmlspecialchars($user[$field] ?? 'N/A');
                                    }
                                    if (in_array($field, $allowed_fields) && ($field !== 'anniversary_date' || ($user['marital_status'] !== 'Single' && !empty($user['marital_status'])))) {
                                        echo ' <i class="fas fa-pencil-alt edit-icon" onclick="openEditModal(\'' . htmlspecialchars($field) . '\', \'' . htmlspecialchars($user[$field] ?? '') . '\', \'' . htmlspecialchars($user['id']) . '\')"></i>';
                                    }
                                    echo '</td>';
                                    echo '</tr>';
                                }
                            }
                            ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="alert alert-danger">Your account details could not be found.</div>
            <?php endif; ?>
        </div>

        <!-- Edit Field Modal -->
        <div class="modal fade" id="editModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header bg-primary text-white">
                        <h5 class="modal-title">Edit Field</h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form id="editForm" method="POST">
                            <input type="hidden" name="user_id" id="modal_user_id" value="<?php echo htmlspecialchars($user_id); ?>">
                            <input type="hidden" name="field_name" id="modal_field_name">
                            <div class="mb-3">
                                <label id="modal_field_label" class="form-label"></label>
                                <div id="modal_input_container"></div>
                            </div>
                            <div class="d-flex justify-content-end">
                                <button type="button" class="btn btn-outline-secondary me-2" data-bs-dismiss="modal">Cancel</button>
                                <button type="submit" class="btn btn-primary">Save</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Photo Upload Modal -->
        <div class="modal fade" id="photoModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header bg-primary text-white">
                        <h5 class="modal-title">Upload Profile Photo</h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form id="photoForm" method="POST" enctype="multipart/form-data">
                            <input type="hidden" name="user_id" value="<?php echo htmlspecialchars($user_id); ?>">
                            <div class="mb-3">
                                <label for="profile_photo" class="form-label">Select Photo (JPG, PNG, GIF, max 2MB)</label>
                                <input type="file" class="form-control" id="profile_photo" name="profile_photo" accept="image/jpeg,image/png,image/gif" required>
                            </div>
                            <div class="d-flex justify-content-end">
                                <button type="button" class="btn btn-outline-secondary me-2" data-bs-dismiss="modal">Cancel</button>
                                <button type="submit" class="btn btn-primary">Upload</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            const content = document.getElementById('content');
            sidebar.classList.toggle('active');
            content.classList.toggle('active');
        }

        // Field options for enum fields
        const fieldOptions = {
            'gender': ['Male', 'Female', 'Others'],
            'marital_status': ['Single', 'Married', 'Divorced']
        };

        // Field types for input validation
        const fieldTypes = {
            'anniversary_date': 'date',
            'date_of_birth': 'date',
            'previous_salary': 'number',
            'no_of_children': 'number',
            'total_experience_years': 'number',
            'email': 'email'
        };

        function openEditModal(fieldName, fieldValue, userId) {
            document.getElementById('modal_user_id').value = userId;
            document.getElementById('modal_field_name').value = fieldName;
            document.getElementById('modal_field_label').textContent = 
                fieldName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
            
            const container = document.getElementById('modal_input_container');
            container.innerHTML = '';
            
            if (fieldOptions[fieldName]) {
                // Create select dropdown for enum fields
                const select = document.createElement('select');
                select.className = 'form-select';
                select.name = 'field_value';
                select.required = true;
                
                fieldOptions[fieldName].forEach(option => {
                    const optionElement = document.createElement('option');
                    optionElement.value = option;
                    optionElement.textContent = option;
                    if (option === fieldValue) optionElement.selected = true;
                    select.appendChild(optionElement);
                });
                
                container.appendChild(select);
            } else if (fieldTypes[fieldName] === 'date') {
                // Date input
                const input = document.createElement('input');
                input.type = 'date';
                input.className = 'form-control';
                input.name = 'field_value';
                input.value = fieldValue;
                container.appendChild(input);
            } else if (fieldTypes[fieldName] === 'number') {
                // Number input
                const input = document.createElement('input');
                input.type = 'number';
                input.className = 'form-control';
                input.name = 'field_value';
                input.value = fieldValue;
                input.step = fieldName.includes('salary') ? '0.01' : '1';
                container.appendChild(input);
            } else if (fieldTypes[fieldName] === 'email') {
                // Email input
                const input = document.createElement('input');
                input.type = 'email';
                input.className = 'form-control';
                input.name = 'field_value';
                input.value = fieldValue;
                container.appendChild(input);
            } else {
                // Default text input
                const input = document.createElement('input');
                input.type = 'text';
                input.className = 'form-control';
                input.name = 'field_value';
                input.value = fieldValue;
                container.appendChild(input);
            }
            
            // Show modal
            const modal = new bootstrap.Modal(document.getElementById('editModal'));
            modal.show();
        }

        function openPhotoModal(userId) {
            const modal = new bootstrap.Modal(document.getElementById('photoModal'));
            modal.show();
        }
    </script>
</body>
</html>