<?php
require_once 'db_connection.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'User is not logged in.']);
    exit();
}

$data = json_decode(file_get_contents('php://input'), true);
$newEmail = $data['new_email'] ?? null;
$currentPassword = $data['current_password'] ?? null;

if (!$newEmail || !$currentPassword) {
    echo json_encode(['success' => false, 'message' => 'Missing email or password.']);
    exit();
}

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

$userId = $_SESSION['user_id'];

try {
    $query = $pdo->prepare("SELECT password FROM users WHERE email_id = :userId");
    $query->bindParam(':userId', $userId, PDO::PARAM_INT);
    $query->execute();
    $user = $query->fetch(PDO::FETCH_ASSOC);

    if (!$user || !password_verify($currentPassword, $user['password'])) {
        echo json_encode(['success' => false, 'message' => 'Incorrect password.']);
        exit();
    }

    $emailQuery = $pdo->prepare("SELECT id FROM emails_v WHERE email = :newEmail");
    $emailQuery->bindParam(':newEmail', $newEmail, PDO::PARAM_STR);
    $emailQuery->execute();
    if ($emailQuery->fetch(PDO::FETCH_ASSOC)) {
        echo json_encode(['success' => false, 'message' => 'Email is already in use.']);
        exit();
    }

    $updateQuery = $pdo->prepare("UPDATE emails_v SET email = :newEmail WHERE id = :userId");
    $updateQuery->bindParam(':newEmail', $newEmail, PDO::PARAM_STR);
    $updateQuery->bindParam(':userId', $userId, PDO::PARAM_INT);
    $updateQuery->execute();

    echo json_encode(['success' => true, 'message' => 'Email updated successfully.']);
} catch (PDOException $e) {
    error_log("Error updating email: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'An error occurred while updating the email.']);
}
?>
