<?php
session_start();
require_once "config.php";

// ✅ Ensure agent is logged in (not admin)
if (!isset($_SESSION["user_id"]) || $_SESSION["role"] !== 'basic' && $_SESSION["role"] !== 'gold' && $_SESSION["role"] !== 'premium') {
    header("Location: login.php");
    exit;
}


$user_id = $_SESSION["user_id"];
$message = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $update_image = false;
    $update_password = false;
    $new_name = null;

    // 1️⃣ Handle Image Upload
    if (!empty($_FILES['profile_image']['name'])) {
        $allowed_ext = ['jpg','jpeg','png','gif'];
        $file_name = $_FILES['profile_image']['name'];
        $file_tmp  = $_FILES['profile_image']['tmp_name'];
        $file_ext  = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

        if (in_array($file_ext, $allowed_ext)) {
            $new_name = "user_" . $user_id . "." . $file_ext;
            $destination = "uploads/" . $new_name;

            if (move_uploaded_file($file_tmp, $destination)) {
                $update_image = true;
            } else {
                $message .= "Failed to upload image. ";
            }
        } else {
            $message .= "Invalid image type. Only JPG, PNG, GIF allowed. ";
        }
    }

    // 2️⃣ Handle Password Change
    $current_password = $_POST['current_password'] ?? '';
    $new_password     = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    if (!empty($current_password) || !empty($new_password) || !empty($confirm_password)) {
        $stmt = $conn->prepare("SELECT password FROM users WHERE id=?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if (!$result) {
            $message .= "User not found. ";
        } elseif (!password_verify($current_password, $result['password'])) {
            $message .= "Current password is incorrect. ";
        } elseif ($new_password !== $confirm_password) {
            $message .= "New passwords do not match. ";
        } else {
            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("UPDATE users SET password=? WHERE id=?");
            $stmt->bind_param("si", $hashed_password, $user_id);
            if ($stmt->execute()) {
                $update_password = true;
            } else {
                $message .= "Failed to update password. ";
            }
            $stmt->close();
        }
    }

    // 3️⃣ Update DB with new image if uploaded
    if ($update_image && $new_name) {
        $stmt = $conn->prepare("UPDATE users SET image=? WHERE id=?");
        $stmt->bind_param("si", $new_name, $user_id);
        if (!$stmt->execute()) {
            $message .= "Failed to update profile image in database. ";
        }
        $stmt->close();
    }

    // ✅ Success / No changes feedback
    if ($update_image || $update_password) {
        $message .= "Profile updated successfully!";
    } elseif (empty($message)) {
        $message = "No changes made.";
    }

    $_SESSION['update_message'] = $message;
    header("Location: agent_dash.php#profile");
    exit;
}
?>
