<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../model/users.php'; // Path to your User model

// Ensure user is logged in before any action
if (!isset($_SESSION['user_email'])) {
    header("Location: ../view/user/index.php"); // Redirect to login if not logged in
    exit();
}

$action = isset($_GET['action']) ? $_GET['action'] : null;

if ($action === 'update_profile' && $_SERVER["REQUEST_METHOD"] == "POST") {
    handleUpdateProfile();
} else {

    header("Location: ../view/user/users.php");
    exit();
}

function handleUpdateProfile() {
    $userModel = new User();
    $originalUserEmail = $_SESSION['user_email']; // Email used for the WHERE clause

    // Basic validation for required fields (can be more extensive)
    if (empty($_POST["first_name"]) || empty($_POST["last_name"]) || empty($_POST["email"])) {
        $_SESSION['profile_message'] = ['type' => 'error', 'text' => 'First name, last name, and email are required.'];
        header("Location: ../view/user/update_profile.php");
        exit();
    }
    if (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
        $_SESSION['profile_message'] = ['type' => 'error', 'text' => 'Invalid email format.'];
        header("Location: ../view/user/update_profile.php");
        exit();
    }
    // Validate gender - ensuring it's one of the allowed values
    $allowedGenders = ['Male', 'Female', 'Other', '']; // Allow empty if not strictly required or to unset
    if (empty($_POST["gender"]) || !in_array($_POST["gender"], $allowedGenders, true)) {
        // If gender is mandatory and not selected, or an invalid value is passed.
        // If gender can be optional and an empty string is acceptable, adjust this logic.
        // For now, let's assume it's okay to be empty or one of the options.
        // If it's strictly required to be Male, Female, or Other, then the condition `empty($_POST["gender"])`
        // should lead to an error, and `''` should be removed from `$allowedGenders`.
        // For this example, we will allow an empty string if submitted, but a dropdown typically forces a selection.
    }

    $posted_first_name = trim($_POST["first_name"]);
    $posted_last_name = trim($_POST["last_name"]);
    $posted_phone = trim($_POST["phone"]);
    $posted_email = trim($_POST["email"]);
    $posted_address = trim($_POST["address"]);
    $posted_city = trim($_POST["city"]);
    $posted_gender = trim($_POST["gender"]); // Retrieve gender
    $posted_full_name = trim($posted_first_name . " " . $posted_last_name);

    // Pass gender to the model method
    $updateResult = $userModel->updateUserProfile($originalUserEmail, $posted_full_name, $posted_email, $posted_phone, $posted_address, $posted_city, $posted_gender);

    if ($updateResult['success']) {
        if (isset($updateResult['affected_rows']) && $updateResult['affected_rows'] > 0) {
            $_SESSION['profile_message'] = ['type' => 'success', 'text' => 'Profile updated successfully.'];
            $_SESSION['user_email'] = $posted_email;       // Update session email
            $_SESSION['user_full_name'] = $posted_full_name; // Update session name
        } else {
            // If success is true but affected_rows is 0, use the message from the model
            $_SESSION['profile_message'] = ['type' => 'success', 'text' => isset($updateResult['message']) ? $updateResult['message'] : 'No changes were made to your profile.'];
        }
    } else {
        // If success is false, use the message from the model, or a generic one
        $_SESSION['profile_message'] = ['type' => 'error', 'text' => isset($updateResult['message']) ? $updateResult['message'] : 'Failed to update profile.'];
    }

    $userModel->closeConnection();

    // Redirect back to the update profile page to show messages and updated form
    header("Location: ../view/user/update_profile.php");
    exit();
}
?>