<?php
require_once '../config/database.php';
secureSessionStart();
requireLogin();

header('Content-Type: application/json');

$conn = getConnection();
$admin_id = $_SESSION['admin_user'];

$user_id = mysqli_real_escape_string($conn, $_POST['user_id'] ?? '');
$email = mysqli_real_escape_string($conn, $_POST['email'] ?? '');

if (empty($user_id) || empty($email)) {
    echo json_encode(['success' => false, 'error' => 'User ID and email are required']);
    exit();
}

// Validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['success' => false, 'error' => 'Invalid email format']);
    exit();
}

// Check if email already exists for another user
$check_query = "SELECT user_id FROM users WHERE email = '$email' AND user_id != '$user_id'";
$check_result = mysqli_query($conn, $check_query);

if (mysqli_num_rows($check_result) > 0) {
    echo json_encode(['success' => false, 'error' => 'Email already exists for another user']);
    exit();
}

// Update email
$query = "UPDATE users SET email = '$email' WHERE user_id = '$user_id'";

if (mysqli_query($conn, $query)) {
    // Log the action
    $log = "INSERT INTO admin_logs (admin_id, action, details, created_at) 
            VALUES ('$admin_id', 'update_user_email', 'Updated email for user: $user_id to $email', NOW())";
    mysqli_query($conn, $log);
    
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['success' => false, 'error' => mysqli_error($conn)]);
}
exit();
?>