<?php
include 'includes/header.php';

// $page_title is now set after language files are loaded by header.php
// Ensure $lang_frontend, $lang_alerts, and $lang_navigation are available from header.php's centralized loader
$page_title = $lang_frontend['PAGE_TITLE_PROFILE'] ?? 'My Profile';
?>

<?php
if (!isLoggedIn()) {
    redirectTo('login');
}

// Get user data
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch();

if (!$user) {
    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_USER_NOT_FOUND'] ?? 'User not found', 'danger');
    redirectTo('index');
}

// Fetch enabled custom fields for profile zone (always, not just on POST)
$custom_fields = [];
try {
    $stmt_cf = $pdo->prepare("SELECT * FROM custom_fields WHERE zone = 'profile' AND is_active = 1 ORDER BY sort_order ASC, id ASC");
    $stmt_cf->execute();
    $custom_fields = $stmt_cf->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $custom_fields = [];
}

// Handle custom field errors from session
$custom_field_errors = $_SESSION['custom_field_errors'] ?? [];
$custom_field_values = $_SESSION['custom_field_values'] ?? [];

$notification_settings_definition = [
    'notify_new_user_registration' => ['label' => $lang_frontend['NOTIFICATION_LABEL_NEW_USER_REGISTRATION'] ?? 'Receive email when a new user registers', 'admin_only' => true],
    'notify_ticket_creation' => ['label' => $lang_frontend['NOTIFICATION_LABEL_TICKET_CREATION'] ?? 'Receive email when a new ticket is created', 'admin_only' => true],
    'notify_ticket_status_change' => ['label' => $lang_frontend['NOTIFICATION_LABEL_TICKET_STATUS_CHANGE'] ?? 'Receive email when a ticket is closed or reopened', 'admin_only' => true],
    'notify_project_task_creation' => ['label' => $lang_frontend['NOTIFICATION_LABEL_PROJECT_TASK_CREATION'] ?? 'Receive email when a task is added to a project', 'admin_only' => true],
    'notify_project_file_upload' => ['label' => $lang_frontend['NOTIFICATION_LABEL_PROJECT_FILE_UPLOAD'] ?? 'Receive email when a file is added to project files', 'admin_only' => true],
    'notify_ticket_comment' => ['label' => $lang_frontend['NOTIFICATION_LABEL_TICKET_COMMENT'] ?? 'Receive email when a comment is added to ticket(s)', 'admin_only' => false],
    'notify_project_task_milestone_change' => ['label' => $lang_frontend['NOTIFICATION_LABEL_PROJECT_TASK_MILESTONE_CHANGE'] ?? 'Receive email when a task is moved to a new milestone', 'admin_only' => false],
    'notify_project_task_completion' => ['label' => $lang_frontend['NOTIFICATION_LABEL_PROJECT_TASK_COMPLETION'] ?? 'Receive email when a task is completed', 'admin_only' => false],
    'notify_project_assignment' => ['label' => $lang_frontend['NOTIFICATION_LABEL_PROJECT_ASSIGNMENT'] ?? 'Receive email when you are assigned to a new project', 'admin_only' => false]
];

// Notification settings for v2.0
$filtered_notification_settings_definition = $notification_settings_definition;


// Fetch user's current notification settings
$stmt_prefs = $pdo->prepare("SELECT * FROM user_notification_settings WHERE user_id = ?");
$stmt_prefs->execute([$_SESSION['user_id']]);
$user_notification_prefs_db = $stmt_prefs->fetch(PDO::FETCH_ASSOC);

$user_notification_prefs = [];
if ($user_notification_prefs_db) {
    foreach ($filtered_notification_settings_definition as $key => $details) {
        $user_notification_prefs[$key] = (bool) $user_notification_prefs_db[$key];
    }
} else {
    // Default all to true if no record exists
    foreach ($filtered_notification_settings_definition as $key => $details) {
        $user_notification_prefs[$key] = true;
    }
}


// Format dates with proper timezone
$registrationDate = getFormattedDate($user['created_at'], DATETIME_FORMAT);
$lastLoginDate = !empty($user['last_login']) ? getFormattedDate($user['last_login'], DATETIME_FORMAT) : ($lang_frontend['TEXT_NEVER'] ?? 'Never');

// Add timezone information to display
$timezoneInfo = "<small class='text-muted'>" . sprintf($lang_frontend['TEXT_DATES_TIMEZONE_NOTE'] ?? 'All dates are shown in %s timezone', TIMEZONE) . "</small>";

// Handle account deletion (GDPR feature)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_account'])) {
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_CSRF_ACCOUNT_NOT_DELETED'] ?? 'Invalid CSRF token. Account not deleted.', 'danger');
        redirectTo(getCleanUrl('profile'));
        exit;
    }

    // Verify this is a regular user (not admin or staff)
    if (!isAdminOrStaff() && defined('GDPR_POLICY') && GDPR_POLICY && defined('ALLOW_REGISTER') && ALLOW_REGISTER) {
        $confirmation_text = sanitizeInput($_POST['confirmation_text'] ?? '');

        if ($confirmation_text !== 'DELETE') {
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_ACCOUNT_DELETION_CONFIRMATION_FAILED'] ?? 'Account deletion confirmation failed. You must type "DELETE" exactly to confirm.', 'danger');
            redirectTo(getCleanUrl('profile'));
            exit;
        }

        try {
            $pdo->beginTransaction();

            $user_id = $_SESSION['user_id'];
            $user_email = $user['email'];

            // Delete all tickets related to this user
            $stmt = $pdo->prepare("DELETE FROM tickets WHERE user_id = ? OR email = ?");
            $stmt->execute([$user_id, $user_email]);

            // Delete user's notification settings
            $stmt = $pdo->prepare("DELETE FROM user_notification_settings WHERE user_id = ?");
            $stmt->execute([$user_id]);

            // Delete user's avatar file if exists
            if (!empty($user['avatar']) && file_exists('uploads/avatars/' . $user['avatar'])) {
                unlink('uploads/avatars/' . $user['avatar']);
            }

            // Delete the user account
            $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
            $stmt->execute([$user_id]);

            $pdo->commit();

            // Log out the user and clear session using SessionManager
            SessionManager::destroy();
            SessionManager::initialize();

            // Set success message for the index page
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_SUCCESS_ACCOUNT_DELETED'] ?? 'Your account has been successfully deleted. All your personal data and tickets have been removed from our system.', 'success');

            // Redirect to home page
            redirectTo('index');
            exit;

        } catch (Exception $e) {
            $pdo->rollBack();
            error_log("Error deleting user account: " . $e->getMessage());
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_ACCOUNT_DELETION_FAILED'] ?? 'An error occurred while deleting your account. Please contact support.', 'danger');
            redirectTo(getCleanUrl('profile'));
            exit;
        }
    } else {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_ACCOUNT_DELETION_NOT_AVAILABLE'] ?? 'Account deletion is not available for your user type or this feature is disabled.', 'danger');
        redirectTo(getCleanUrl('profile'));
        exit;
    }
}

// Update profile
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['delete_account'])) {
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_INVALID_CSRF'] ?? 'Invalid CSRF token. Please try again.', 'danger');
        redirectTo(getCleanUrl('profile'));
        exit;
    }

    $name = sanitizeInput($_POST['name']);
    $address = sanitizeInput($_POST['address']);
    $state = sanitizeInput($_POST['state']);
    $zipcode = sanitizeInput($_POST['zipcode']);
    $company = sanitizeInput($_POST['company']);
    $country_code = (defined('ENABLE_LOCATION_FIELDS') && ENABLE_LOCATION_FIELDS && isset($_POST['country_code'])) ? sanitizeInput($_POST['country_code']) : $user['country_code']; // Keep old if not set or feature disabled
    $city = (defined('ENABLE_LOCATION_FIELDS') && ENABLE_LOCATION_FIELDS && isset($_POST['city'])) ? sanitizeInput($_POST['city']) : $user['city']; // Keep old if not set or feature disabled

    $remove_avatar = isset($_POST['remove_avatar']) && $_POST['remove_avatar'] == '1';

    $current_password = $_POST['current_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    // Basic validation
    if (empty($name)) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_NAME_CANNOT_BE_EMPTY'] ?? 'Name cannot be empty', 'danger');
    } elseif (defined('ENABLE_LOCATION_FIELDS') && ENABLE_LOCATION_FIELDS && empty($country_code) && isset($_POST['country_code'])) {
        // Only trigger if location fields are enabled AND country was submitted as empty
        // If country_code wasn't in POST, it means the fields might not have been shown, 
        // or user didn't intend to change it if it was already set and fields were hidden by some other logic.
        // The $country_code variable at this point already holds $user['country_code'] if not in POST.
        // So, we check if $_POST['country_code'] was specifically sent and is empty.
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_COUNTRY_REQUIRED_PROFILE'] ?? 'Country is a required field when location fields are enabled.', 'danger');
    } else {
        $avatar = $user['avatar']; // Keep old avatar by default
        $new_avatar_uploaded_successfully = false;

        // Handle avatar removal first
        if ($remove_avatar && !empty($user['avatar'])) {
            $avatar_path_to_remove = 'uploads/avatars/' . $user['avatar'];
            if (file_exists($avatar_path_to_remove)) {
                unlink($avatar_path_to_remove);
            }
            $avatar = null; // Set avatar to null for database update
            $_SESSION['avatar'] = null; // Update session immediately
            // If avatar is removed, don't process new upload in the same request
        } elseif (!empty($_FILES['avatar']['name'])) { // Process new avatar upload only if not removing
            $is_valid_image = false;
            if (function_exists('getimagesize') && is_uploaded_file($_FILES['avatar']['tmp_name'])) {
                $image_info = @getimagesize($_FILES['avatar']['tmp_name']);
                if ($image_info) {
                    $is_valid_image = true;
                } else {
                    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_WARNING_AVATAR_INVALID_IMAGE_PROFILE_UPDATED'] ?? 'New avatar is not a valid image. Please upload a valid image file (e.g., JPG, PNG, GIF). Profile updated without changing avatar.', 'warning');
                }
            } else if (!is_uploaded_file($_FILES['avatar']['tmp_name'])) {
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_WARNING_AVATAR_UPLOAD_ERROR_PROFILE_UPDATED'] ?? 'Avatar upload error. Please try again. Profile updated without changing avatar.', 'warning');
            }

            if ($is_valid_image) {
                $new_avatar_filename = uploadFile($_FILES['avatar'], 'uploads/avatars/');
                if ($new_avatar_filename && $new_avatar_filename !== '') { // uploadFile returns filename on success
                    // Successfully uploaded new avatar
                    if (!empty($user['avatar']) && $user['avatar'] !== $new_avatar_filename && file_exists('uploads/avatars/' . $user['avatar'])) {
                        unlink('uploads/avatars/' . $user['avatar']);
                    }
                    $avatar = $new_avatar_filename; // Update to new avatar
                    $_SESSION['avatar'] = $avatar; // Update session immediately
                    $new_avatar_uploaded_successfully = true;
                    // Alert for successful avatar change can be combined with general profile update message later
                } elseif ($new_avatar_filename === false) { // Explicit false from uploadFile means size/extension validation error
                    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_WARNING_AVATAR_UPLOAD_FAILED_TYPE_SIZE_PROFILE_UPDATED'] ?? 'New avatar upload failed. Invalid file type or size. Profile updated without changing avatar.', 'warning');
                } else { // Empty string from uploadFile means move_uploaded_file failed
                    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_WARNING_AVATAR_UPLOAD_FAILED_SERVER_PROFILE_UPDATED'] ?? 'New avatar upload failed due to a server error. Profile updated without changing avatar.', 'warning');
                }
            }
        }

        // Check if password change is requested
        if (!empty($current_password) && !empty($new_password)) {
            if (!password_verify($current_password, $user['password'])) {
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_CURRENT_PASSWORD_INCORRECT'] ?? 'Current password is incorrect', 'danger');
            } elseif ($new_password !== $confirm_password) {
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_NEW_PASSWORDS_NO_MATCH'] ?? 'New passwords do not match', 'danger');
            } elseif (strlen($new_password) < 8) {
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_PASSWORD_MIN_LENGTH'] ?? 'Password must be at least 8 characters long', 'danger');
            } else {
                // Update password
                $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("UPDATE users SET name = ?, company = ?, avatar = ?, password = ?, country_code = ?, city = ?, address = ?, zipcode = ?, state = ? WHERE id = ?");
                $stmt->execute([$name, $company, $avatar, $hashed_password, $country_code, $city, $address, $zipcode, $state, $_SESSION['user_id']]);

                // Regenerate session ID and update state for security
                session_regenerate_id(true);
                SessionManager::updateSessionState();

                $_SESSION['name'] = $name;
                $_SESSION['avatar'] = $avatar;
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_SUCCESS_PROFILE_UPDATED_NEW_PASSWORD'] ?? 'Profile updated successfully with new password');
                redirectTo(getCleanUrl('profile'));
            }
        } else {
            // Update profile without changing password
            $stmt = $pdo->prepare("UPDATE users SET name = ?, company = ?, avatar = ?, country_code = ?, city = ?, address = ?, zipcode = ?, state = ? WHERE id = ?");
            $stmt->execute([$name, $company, $avatar, $country_code, $city, $address, $zipcode, $state, $_SESSION['user_id']]);

            // Regenerate session ID and update state for security
            session_regenerate_id(true);
            SessionManager::updateSessionState();

            $_SESSION['name'] = $name;
            $_SESSION['avatar'] = $avatar;
            // Profile data updated, now handle notification settings
            // Success message will be set after processing notifications
        }

        // Process Notification Settings
        $current_user_id = $_SESSION['user_id'];
        $is_admin_user = isAdminOrStaff(); // Allow both admin and staff to access admin-only notifications

        $notification_values_to_save = [];
        foreach ($filtered_notification_settings_definition as $key => $details) {
            if ($details['admin_only'] && !$is_admin_user) {
                // If the setting is admin-only and the user is not an admin,
                // retain the existing value from DB or default to true if not in DB.
                // This prevents non-admins from changing admin-only settings.
                // However, if their role changes, these settings should be respected.
                // For simplicity, we fetch existing or default to true (as per table default).
                $notification_values_to_save[$key] = $user_notification_prefs_db ? (int) $user_notification_prefs_db[$key] : 1;
            } else {
                // For non-admin settings OR if user is an admin, take value from POST
                $notification_values_to_save[$key] = isset($_POST[$key]) ? 1 : 0;
            }
        }

        // Check if user settings already exist
        $stmt_check = $pdo->prepare("SELECT id FROM user_notification_settings WHERE user_id = ?");
        $stmt_check->execute([$current_user_id]);
        $existing_settings_id = $stmt_check->fetchColumn();

        if ($existing_settings_id) {
            // Update existing settings
            $sql_update_prefs = "UPDATE user_notification_settings SET 
                    notify_new_user_registration = :notify_new_user_registration,
                    notify_ticket_creation = :notify_ticket_creation,
                    notify_ticket_status_change = :notify_ticket_status_change,
                    notify_ticket_comment = :notify_ticket_comment,
                    notify_project_task_creation = :notify_project_task_creation,
                    notify_project_task_milestone_change = :notify_project_task_milestone_change,
                    notify_project_task_completion = :notify_project_task_completion,
                    notify_project_file_upload = :notify_project_file_upload,
                    notify_project_assignment = :notify_project_assignment,
                    updated_at = CURRENT_TIMESTAMP
                WHERE user_id = :user_id";
            $stmt_save_prefs = $pdo->prepare($sql_update_prefs);
        } else {
            // Insert new settings
            $sql_insert_prefs = "INSERT INTO user_notification_settings (user_id, 
                    notify_new_user_registration, notify_ticket_creation, notify_ticket_status_change,
                    notify_ticket_comment, notify_project_task_creation, notify_project_task_milestone_change,
                    notify_project_task_completion, notify_project_file_upload, notify_project_assignment) 
                VALUES (:user_id, 
                    :notify_new_user_registration, :notify_ticket_creation, :notify_ticket_status_change,
                    :notify_ticket_comment, :notify_project_task_creation, :notify_project_task_milestone_change,
                    :notify_project_task_completion, :notify_project_file_upload, :notify_project_assignment)";
            $stmt_save_prefs = $pdo->prepare($sql_insert_prefs);
        }

        $notification_values_to_save['user_id'] = $current_user_id;

        try {
            $stmt_save_prefs->execute($notification_values_to_save);
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_SUCCESS_PROFILE_NOTIFICATIONS_UPDATED'] ?? 'Profile and notification settings updated successfully');
        } catch (PDOException $e) {
            error_log("Error saving notification settings: " . $e->getMessage());
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_PROFILE_UPDATED_NOTIFICATION_SAVE_FAILED'] ?? 'Profile updated, but there was an error saving notification settings. Please try again.', 'danger');
        }

        // Validate and save custom field values
        $custom_field_errors = [];
        $custom_field_values = [];

        if (!empty($custom_fields)) {
            foreach ($custom_fields as $cf) {
                $field_id = $cf['id'];
                $field_name = 'custom_field_' . $field_id;
                $value = '';

                if ($cf['type'] === 'checkboxes') {
                    $value = isset($_POST[$field_name]) ? implode(',', (array) $_POST[$field_name]) : '';
                } elseif ($cf['type'] === 'checkbox') {
                    $value = isset($_POST[$field_name]) ? '1' : '0';
                } else {
                    $value = isset($_POST[$field_name]) ? trim($_POST[$field_name]) : '';
                }

                // Validate required fields
                if ($cf['required'] && ($value === '' || ($cf['type'] === 'checkboxes' && empty($value)))) {
                    $custom_field_errors[$cf['id']] = 'This field is required.';
                }
                
                // Enforce length limits based on field type
                if (!empty($value) && is_string($value)) {
                    $max_length = 5000; // Default max length
                    if ($cf['type'] === 'textarea') {
                        $max_length = 10000;
                    } elseif (in_array($cf['type'], ['text', 'email', 'url'])) {
                        $max_length = 500;
                    }
                    
                    if (strlen($value) > $max_length) {
                        $custom_field_errors[$cf['id']] = "Field value exceeds maximum length of {$max_length} characters.";
                    } else {
                        // Truncate if necessary (but this shouldn't happen with proper validation)
                        $value = substr($value, 0, $max_length);
                    }
                }

                $custom_field_values[$cf['id']] = $value;
            }

            // If validation errors, store values in session and redirect
            if (!empty($custom_field_errors)) {
                $_SESSION['custom_field_errors'] = $custom_field_errors;
                $_SESSION['custom_field_values'] = $custom_field_values;
                $_SESSION['alert'] = displayAlert('Please fill in all required custom fields.', 'danger');
                redirectTo(getCleanUrl('profile'));
                exit;
            }

            // Save custom field values
            foreach ($custom_fields as $cf) {
                $field_id = $cf['id'];
                $value = $custom_field_values[$field_id];

                // Check if value exists
                $stmt_check = $pdo->prepare("SELECT id FROM custom_field_values WHERE field_id = ? AND item_id = ?");
                $stmt_check->execute([$field_id, $_SESSION['user_id']]);
                $existing_id = $stmt_check->fetchColumn();

                if ($existing_id) {
                    // Update
                    $stmt_update = $pdo->prepare("UPDATE custom_field_values SET value = ? WHERE id = ?");
                    $stmt_update->execute([$value, $existing_id]);
                } else {
                    // Insert
                    $stmt_insert = $pdo->prepare("INSERT INTO custom_field_values (field_id, value, item_id) VALUES (?, ?, ?)");
                    $stmt_insert->execute([$field_id, $value, $_SESSION['user_id']]);
                }
            }
        }

        // Clear any previous custom field errors/values from session
        unset($_SESSION['custom_field_errors']);
        unset($_SESSION['custom_field_values']);

        redirectTo(getCleanUrl('profile'));
    } // Closes the "else" for if (empty($name)) [originally L65, content starts L68]
} // Closes the if ($_SERVER['REQUEST_METHOD'] === 'POST') [originally L50]
?>

<div class="row">
    <div class="col-md-4">
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">
                    <?php echo $lang_frontend['PROFILE_CARD_YOUR_PROFILE_TITLE'] ?? ($lang_frontend['HOME_PROFILE_TITLE'] ?? 'Your Profile'); ?>
                </h5>
            </div>
            <div class="card-body text-center">
                <?php if (!empty($user['avatar'])): ?>
                    <img src="uploads/avatars/<?php echo $user['avatar']; ?>" alt="Avatar" class="avatar-lg mb-3">
                <?php else: ?>
                    <div
                        class="avatar-lg mx-auto mb-3 bg-primary d-flex justify-content-center align-items-center text-white">
                        <i class="bi bi-person" style="font-size: 3rem;"></i>
                    </div>
                <?php endif; ?>

                <h3><?php echo $user['name']; ?></h3>
                <p class="text-muted"><?php echo $user['email']; ?></p>

                <?php if (!empty($user['company'])): ?>
                    <p><i class="bi bi-building"></i> <?php echo $user['company']; ?></p>
                <?php endif; ?>

                <p>
                    <span
                        class="badge bg-<?php echo $user['role'] === 'admin' ? 'danger' : ($user['role'] === 'staff' ? 'secondary' : 'primary'); ?>">
                        <?php echo ucfirst($user['role']); ?>
                    </span>
                </p>

                <p><small><?php echo sprintf($lang_frontend['PROFILE_TEXT_MEMBER_SINCE'] ?? 'Member since: %s', getFormattedDate($user['created_at'], 'F d, Y')); ?></small>
                </p>
            </div>
        </div>
        <?php if (isAdmin()): ?>
        <?php else: ?>
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><?php echo $lang_frontend['FOOTER_QUICK_LINKS'] ?? 'Quick Links'; ?></h5>
                </div>
                <div class="card-body">
                    <div class="d-grid gap-2">
                        <a href="tickets" class="btn btn-outline-primary">
                            <i class="bi bi-ticket"></i>
                            <?php echo $lang_frontend['PROFILE_BUTTON_MY_TICKETS'] ?? 'My Tickets'; ?>
                        </a>
                        <?php if (isLoggedIn() && defined('ENABLE_PROJECTS') && ENABLE_PROJECTS): ?>
                            <a href="projects" class="btn btn-outline-primary">
                                <i class="bi bi-kanban"></i>
                                <?php echo $lang_frontend['PROFILE_BUTTON_MY_PROJECTS'] ?? 'My Projects'; ?>
                            </a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <?php if (!isAdminOrStaff() && defined('GDPR_POLICY') && GDPR_POLICY && defined('ALLOW_REGISTER') && ALLOW_REGISTER): ?>
            <!-- GDPR Delete Account Card -->
            <div class="card border-danger">
                <div class="card-header bg-danger text-white">
                    <h5 class="mb-0"><i class="bi bi-exclamation-triangle"></i>
                        <?php echo $lang_frontend['PROFILE_DELETE_ACCOUNT_TITLE'] ?? 'Delete Account'; ?></h5>
                </div>
                <div class="card-body">
                    <p class="text-danger">
                        <strong><?php echo $lang_frontend['PROFILE_DELETE_WARNING_PERMANENT'] ?? 'Warning: This action will permanently delete your account and all associated data.'; ?></strong>
                    </p>
                    <ul class="small text-muted">
                        <li><?php echo $lang_frontend['PROFILE_DELETE_WARNING_ITEM_PROFILE'] ?? 'Your profile information will be removed'; ?>
                        </li>
                        <li><?php echo $lang_frontend['PROFILE_DELETE_WARNING_ITEM_TICKETS'] ?? 'All your tickets will be deleted'; ?>
                        </li>
                        <li><?php echo $lang_frontend['PROFILE_DELETE_WARNING_ITEM_UNDONE'] ?? 'This action cannot be undone'; ?>
                        </li>
                    </ul>
                    <button type="button" class="btn btn-danger btn-sm w-100" data-bs-toggle="modal"
                        data-bs-target="#deleteAccountModal">
                        <i class="bi bi-trash"></i>
                        <?php echo $lang_frontend['PROFILE_BUTTON_DELETE_MY_ACCOUNT'] ?? 'Delete My Account'; ?>
                    </button>
                </div>
            </div>
        <?php endif; ?>


    </div>

    <div class="col-md-8">
        <div class="card">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0"><?php echo $lang_frontend['PROFILE_CARD_EDIT_PROFILE_TITLE'] ?? 'Edit Profile'; ?></h5>
            </div>
            <div class="card-body">
                <form action="<?php echo getCleanUrl('profile'); ?>" method="post" enctype="multipart/form-data">
                    <?php echo get_csrf_input_field(); ?>
                    <div class="mb-3">
                        <label for="company"
                            class="form-label"><?php echo $lang_frontend['FORM_LABEL_COMPANY'] ?? 'Company'; ?></label>
                        <input type="text" class="form-control" id="company" name="company"
                            value="<?php echo htmlspecialchars($user['company'] ?? ''); ?>">
                    </div>


                    <div class="mb-3">
                        <label for="name"
                            class="form-label"><?php echo $lang_frontend['FORM_LABEL_FULL_NAME'] ?? 'Full Name'; ?></label>
                        <input type="text" class="form-control" id="name" name="name"
                            value="<?php echo $user['name']; ?>" required>
                    </div>

                    <div class="mb-3">
                        <label for="email"
                            class="form-label"><?php echo $lang_frontend['FORM_LABEL_EMAIL'] ?? 'Email Address'; ?></label>
                        <input type="email" class="form-control" value="<?php echo $user['email']; ?>" readonly
                            disabled>
                        <div class="form-text">
                            <?php echo $lang_frontend['PROFILE_FORM_TEXT_EMAIL_CANNOT_CHANGE'] ?? 'Email address cannot be changed'; ?>
                        </div>
                    </div>

                    <?php if (defined('ENABLE_LOCATION_FIELDS') && ENABLE_LOCATION_FIELDS): ?>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="country_code"
                                    class="form-label"><?php echo $lang_frontend['FORM_LABEL_COUNTRY'] ?? 'Country'; ?>
                                    <span class="text-danger">*</span></label>
                                <select class="form-select" id="country_code" name="country_code" required>
                                    <option value="">
                                        <?php echo $lang_frontend['FORM_OPTION_SELECT_COUNTRY'] ?? '-- Select Country --'; ?>
                                    </option>
                                    <?php
                                    $countries = get_country_list();
                                    $current_country = $user['country_code'];
                                    foreach ($countries as $code => $country_name): ?>
                                        <option value="<?php echo htmlspecialchars($code); ?>" <?php echo ($code === $current_country) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($country_name); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="city"
                                    class="form-label"><?php echo $lang_frontend['FORM_LABEL_CITY'] ?? 'City'; ?></label>
                                <input type="text" class="form-control" id="city" name="city"
                                    value="<?php echo htmlspecialchars($user['city'] ?? ''); ?>">
                            </div>
                            <div class="col-md-12 mb-3">
                                <label for="name"
                                    class="form-label"><?php echo $lang_frontend['FORM_ADDRES'] ?? 'Address'; ?></label>
                                <input type="text" class="form-control" id="address" name="address"
                                    value="<?php echo $user['address']; ?>">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="name"
                                    class="form-label"><?php echo $lang_frontend['FORM_STATE'] ?? 'State'; ?></label>
                                <input type="text" class="form-control" id="state" name="state"
                                    value="<?php echo $user['state']; ?>">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="name"
                                    class="form-label"><?php echo $lang_frontend['FORM_ZIPCODE'] ?? 'Zip Code'; ?></label>
                                <input type="text" class="form-control" id="zipcode" name="zipcode"
                                    value="<?php echo $user['zipcode']; ?>">
                            </div>

                        </div>
                    <?php endif; ?>

                    <?php foreach ($custom_fields as $cf):
                        $field_name = 'custom_field_' . $cf['id'];
                        $field_label = htmlspecialchars($cf['name']);
                        $is_required = $cf['required'] ? ' <span class="text-danger">*</span>' : '';
                        $possible_values = array_filter(array_map('trim', explode(',', $cf['possible_values'])));
                        $value = '';
                        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                            $value = isset($_POST[$field_name]) ? $_POST[$field_name] : '';
                        } elseif (isset($_SESSION['custom_field_values'][$cf['id']])) {
                            $value = $_SESSION['custom_field_values'][$cf['id']];
                        } else {
                            $stmt_val = $pdo->prepare("SELECT value FROM custom_field_values WHERE field_id = ? AND item_id = ?");
                            $stmt_val->execute([$cf['id'], $_SESSION['user_id']]);
                            $value = $stmt_val->fetchColumn();
                            if ($cf['type'] === 'radio' && ($value === false || $value === null || $value === '')) {
                                $value = !empty($possible_values) ? $possible_values[0] : '';
                            }
                            if ($cf['type'] === 'checkboxes') {
                                $value = ($value === false || $value === null || $value === '') ? [] : explode(',', $value);
                            }
                            if ($cf['type'] === 'checkbox') {
                                $value = ($value === '1') ? '1' : '0';
                            }
                        }
                        ?>
                        <div class="mb-3">
                            <label class="form-label"><?php echo $field_label . $is_required; ?></label>
                            <?php if ($cf['type'] === 'text'): ?>
                                <input type="text" class="form-control" name="<?php echo $field_name; ?>"
                                    value="<?php echo htmlspecialchars($value); ?>" <?php echo $cf['required'] ? 'required' : ''; ?>>
                            <?php elseif ($cf['type'] === 'textarea'): ?>
                                <textarea class="form-control" name="<?php echo $field_name; ?>" rows="3" <?php echo $cf['required'] ? 'required' : ''; ?>><?php echo htmlspecialchars($value); ?></textarea>
                            <?php elseif ($cf['type'] === 'checkbox'): ?>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="<?php echo $field_name; ?>" value="1"
                                        id="cf_<?php echo $cf['id']; ?>" <?php echo $value == '1' ? 'checked' : ''; ?>>
                                    <label class="form-check-label"
                                        for="cf_<?php echo $cf['id']; ?>"><?php echo $field_label; ?></label>
                                </div>
                            <?php elseif ($cf['type'] === 'checkboxes'): ?>
                                <div class="d-flex flex-column gap-1">
                                    <?php foreach ($possible_values as $pv): ?>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="<?php echo $field_name; ?>[]"
                                                value="<?php echo htmlspecialchars($pv); ?>"
                                                id="cf_<?php echo $cf['id'] . '_' . md5($pv); ?>" <?php echo (is_array($value) && in_array($pv, $value)) || (is_string($value) && in_array($pv, explode(',', $value))) ? 'checked' : ''; ?>>
                                            <label class="form-check-label"
                                                for="cf_<?php echo $cf['id'] . '_' . md5($pv); ?>"><?php echo htmlspecialchars($pv); ?></label>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php elseif ($cf['type'] === 'select'): ?>
                                <select class="form-select" name="<?php echo $field_name; ?>" <?php echo $cf['required'] ? 'required' : ''; ?>>
                                    <option value="">-- Select --</option>
                                    <?php foreach ($possible_values as $pv): ?>
                                        <option value="<?php echo htmlspecialchars($pv); ?>" <?php echo $value == $pv ? 'selected' : ''; ?>><?php echo htmlspecialchars($pv); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            <?php elseif ($cf['type'] === 'radio'): ?>
                                <div class="d-flex flex-column gap-1">
                                    <?php foreach ($possible_values as $pv): ?>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="<?php echo $field_name; ?>"
                                                value="<?php echo htmlspecialchars($pv); ?>"
                                                id="cf_<?php echo $cf['id'] . '_' . md5($pv); ?>" <?php echo $value == $pv ? 'checked' : ''; ?>>
                                            <label class="form-check-label"
                                                for="cf_<?php echo $cf['id'] . '_' . md5($pv); ?>"><?php echo htmlspecialchars($pv); ?></label>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                            <?php if (!empty($custom_field_errors[$cf['id']])): ?>
                                <div class="text-danger small mt-1"><?php echo $custom_field_errors[$cf['id']]; ?></div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>

                    <div class="mb-3">
                        <label for="avatar"
                            class="form-label"><?php echo $lang_frontend['PROFILE_FORM_LABEL_PROFILE_PICTURE'] ?? 'Profile Picture'; ?></label>
                        <input type="file" class="form-control" id="avatar" name="avatar" accept="image/*"
                            data-max-size="<?php echo MAX_UPLOAD_SIZE; ?>" data-allowed-types="jpg,jpeg,png,gif,svg">
                        <div class="form-text">
                            <?php echo $lang_frontend['PROFILE_FORM_TEXT_AVATAR_LEAVE_BLANK'] ?? 'Leave blank to keep current profile picture.'; ?>
                        </div>
                    </div>
                    <?php if (!empty($user['avatar'])): ?>
                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" name="remove_avatar" id="remove_avatar"
                                value="1">
                            <label class="form-check-label" for="remove_avatar">
                                <?php echo sprintf($lang_frontend['PROFILE_FORM_LABEL_REMOVE_AVATAR'] ?? 'Remove current avatar (%s)', htmlspecialchars($user['avatar'])); ?>
                            </label>
                        </div>
                    <?php endif; ?>
                    <div class="form-text">
                        <?php echo sprintf($lang_frontend['FORM_TEXT_MAX_FILE_SIZE'] ?? 'Max file size: %sMB.', MAX_UPLOAD_SIZE / 1024 / 1024); ?>
                        <br><br>
                    </div>

                    <hr>
                    <?php if ((defined('ALLOW_PASSWORD_CHANGE') && ALLOW_PASSWORD_CHANGE) || isAdmin()): ?>
                        <h5 class="mb-3">
                            <?php echo $lang_frontend['PROFILE_HEADING_CHANGE_PASSWORD'] ?? 'Change Password'; ?></h5>
                        <div class="mb-3">
                            <label for="current_password"
                                class="form-label"><?php echo $lang_frontend['FORM_LABEL_CURRENT_PASSWORD'] ?? 'Current Password'; ?></label>
                            <input type="password" class="form-control" id="current_password" name="current_password">
                        </div>

                        <div class="mb-3">
                            <label for="new_password"
                                class="form-label"><?php echo $lang_frontend['FORM_LABEL_NEW_PASSWORD'] ?? 'New Password'; ?></label>
                            <input type="password" class="form-control" id="new_password" name="new_password">
                        </div>

                        <div class="mb-3">
                            <label for="confirm_password"
                                class="form-label"><?php echo $lang_frontend['FORM_LABEL_CONFIRM_NEW_PASSWORD'] ?? 'Confirm New Password'; ?></label>
                            <input type="password" class="form-control" id="confirm_password" name="confirm_password">
                            <div class="form-text">
                                <?php echo $lang_frontend['PROFILE_FORM_TEXT_PASSWORD_LEAVE_BLANK'] ?? "Leave password fields blank if you don't want to change your password"; ?>
                            </div>
                        </div>


                    <?php endif; ?>
                    <div class="d-grid">
                        <button type="submit"
                            class="btn btn-primary btn-lg"><?php echo $lang_frontend['PROFILE_BUTTON_UPDATE_PROFILE'] ?? 'Update Profile'; ?></button>
                    </div>
                    <hr class="my-4">
                    <h5 class="mb-3">
                        <?php echo $lang_frontend['PROFILE_HEADING_NOTIFICATION_SETTINGS'] ?? 'Notification Settings'; ?>
                    </h5>
                    <?php
                    $is_current_user_admin = isAdmin(); // Check if the logged-in user is an admin
                    foreach ($filtered_notification_settings_definition as $key => $details):
                        $is_checked = $user_notification_prefs[$key] ?? true; // Default to true (checked)
                    
                        // Skip non-admin settings if the user is not an admin and this setting is admin_only
                        if ($details['admin_only'] && !$is_current_user_admin) {
                            // Optionally, you could show them as disabled, but hiding is cleaner.
                            // If you want to show them as disabled:
                            // echo '<div class="form-check form-switch mb-2">';
                            // echo '<input class="form-check-input" type="checkbox" id="' . $key . '" name="' . $key . '" value="1" ' . ($is_checked ? 'checked' : '') . ' disabled>';
                            // echo '<label class="form-check-label" for="' . $key . '">' . htmlspecialchars($details['label']) . ' (Admin only - read-only)</label>'; // Potentially localize ' (Admin only - read-only)'
                            // echo '</div>';
                            continue; // Skip rendering this checkbox if user is not admin and setting is admin_only
                        }
                        ?>
                        <div class="form-check form-switch mb-2">
                            <input class="form-check-input" type="checkbox" role="switch" id="<?php echo $key; ?>"
                                name="<?php echo $key; ?>" value="1" <?php echo $is_checked ? 'checked' : ''; ?>>
                            <label class="form-check-label" for="<?php echo $key; ?>">
                                <?php echo htmlspecialchars($details['label']); ?>
                                <?php if ($details['admin_only']): ?>
                                    <span
                                        class="badge bg-info text-dark ms-1"><?php echo $lang_frontend['BADGE_ADMIN_ONLY'] ?? 'Admin only'; ?></span>
                                <?php endif; ?>
                            </label>
                        </div>
                    <?php endforeach; ?>
                    <?php if (isAdmin()): ?>

                    <?php endif; ?>

                </form> <!-- This closes the main form -->
            </div> <!-- This closes card-body -->
        </div> <!-- This closes card -->
    </div> <!-- This closes col-md-8 -->
</div> <!-- This closes row -->

<!-- Delete Account Modal -->
<?php if (!isAdminOrStaff() && defined('GDPR_POLICY') && GDPR_POLICY && defined('ALLOW_REGISTER') && ALLOW_REGISTER): ?>
    <div class="modal fade" id="deleteAccountModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title"><i class="bi bi-exclamation-triangle"></i>
                        <?php echo $lang_frontend['PROFILE_MODAL_CONFIRM_DELETE_TITLE'] ?? 'Confirm Account Deletion'; ?>
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"
                        aria-label="<?php echo $lang_frontend['ARIA_LABEL_CLOSE'] ?? 'Close'; ?>"></button>
                </div>
                <form action="<?php echo getCleanUrl('profile'); ?>" method="post">
                    <?php echo get_csrf_input_field(); ?>
                    <input type="hidden" name="delete_account" value="1">
                    <div class="modal-body">
                        <div class="alert alert-danger">
                            <h6><i class="bi bi-exclamation-triangle"></i>
                                <?php echo $lang_frontend['PROFILE_MODAL_DELETE_IRREVERSIBLE_HEADING'] ?? 'This action is irreversible!'; ?>
                            </h6>
                            <p class="mb-0">
                                <?php echo $lang_frontend['PROFILE_MODAL_DELETE_IRREVERSIBLE_TEXT'] ?? 'Your account and all associated data will be permanently deleted:'; ?>
                            </p>
                        </div>

                        <ul class="list-unstyled mb-4">
                            <li><i class="bi bi-check text-danger"></i>
                                <?php echo $lang_frontend['PROFILE_DELETE_WARNING_ITEM_PROFILE'] ?? 'Profile information'; ?>
                            </li>
                            <li><i class="bi bi-check text-danger"></i>
                                <?php echo $lang_frontend['PROFILE_DELETE_WARNING_ITEM_TICKETS'] ?? "All tickets you've created"; ?>
                            </li>
                            <li><i class="bi bi-check text-danger"></i>
                                <?php echo $lang_frontend['NOTIFICATION_SETTINGS'] ?? 'Notification preferences'; ?></li>
                            <li><i class="bi bi-check text-danger"></i>
                                <?php echo $lang_frontend['PROFILE_DELETE_WARNING_ITEM_AVATAR'] ?? 'Profile picture'; ?>
                            </li>
                        </ul>

                        <p><strong><?php echo $lang_frontend['PROFILE_MODAL_DELETE_CONFIRM_INSTRUCTION'] ?? 'To confirm deletion, please type <code>DELETE</code> in the box below:'; ?></strong>
                        </p>
                        <input type="text" class="form-control" name="confirmation_text"
                            placeholder="<?php echo $lang_frontend['PROFILE_MODAL_DELETE_CONFIRM_PLACEHOLDER'] ?? 'Type DELETE to confirm'; ?>"
                            required>

                        <div class="form-text">
                            <?php echo $lang_frontend['PROFILE_MODAL_DELETE_GDPR_NOTE'] ?? 'This action complies with GDPR data deletion requirements.'; ?>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary"
                            data-bs-dismiss="modal"><?php echo $lang_frontend['BUTTON_CANCEL'] ?? 'Cancel'; ?></button>
                        <button type="submit" class="btn btn-danger">
                            <i class="bi bi-trash"></i>
                            <?php echo $lang_frontend['PROFILE_BUTTON_DELETE_MY_ACCOUNT'] ?? 'Delete My Account'; ?>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
<?php endif; ?>

<?php include 'includes/footer.php'; ?>