<?php
require_once __DIR__ . '/../config/cors.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/EmailSender.php';

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

$json = file_get_contents('php://input');
$data = json_decode($json, true);

$token = trim($data['token'] ?? '');
$newEmail = trim($data['new_email'] ?? '');

if (empty($token) || empty($newEmail)) {
    echo json_encode(['success' => false, 'message' => 'Token and New Email are required.']);
    exit;
}

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

try {
    // 1. Verify token
    $stmt = $pdo->prepare("SELECT * FROM email_change_requests WHERE token = ? AND expires_at > NOW()");
    $stmt->execute([$token]);
    $request = $stmt->fetch();

    if (!$request) {
        echo json_encode(['success' => false, 'message' => 'Invalid or expired token. Please request another email change.']);
        exit;
    }

    $userId = $request['user_id'];
    $userType = $request['user_type'];

    // 2. Check if new email already exists
    if ($userType === 'admin') {
        $checkStmt = $pdo->prepare("SELECT id FROM admins WHERE email = ? AND id != ?");
        $checkStmt->execute([$newEmail, $userId]);
    } else {
        $checkStmt = $pdo->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
        $checkStmt->execute([$newEmail, $userId]);
    }

    if ($checkStmt->fetch()) {
        echo json_encode(['success' => false, 'message' => 'This email is already in use by another account.']);
        exit;
    }

    // 3. Update Email
    $pdo->beginTransaction();

    if ($userType === 'admin') {
        $updateStmt = $pdo->prepare("UPDATE admins SET email = ? WHERE id = ?");
        $updateStmt->execute([$newEmail, $userId]);

        $userStmt = $pdo->prepare("SELECT username, first_name, last_name FROM admins WHERE id = ?");
        $userStmt->execute([$userId]);
        $user = $userStmt->fetch();
        $fullName = trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''));
        if (empty($fullName))
            $fullName = $user['username'] ?? 'Admin';
    } else {
        $updateStmt = $pdo->prepare("UPDATE users SET email = ? WHERE id = ?");
        $updateStmt->execute([$newEmail, $userId]);

        $userStmt = $pdo->prepare("SELECT nroi_id, first_name, last_name FROM users WHERE id = ?");
        $userStmt->execute([$userId]);
        $user = $userStmt->fetch();
        $fullName = trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''));
        if (empty($fullName))
            $fullName = $user['nroi_id'] ?? 'User';
    }

    // Delete request
    $pdo->prepare("DELETE FROM email_change_requests WHERE id = ?")->execute([$request['id']]);

    $pdo->commit();

    // 4. Send notification to NEW email
    sendEmailChangeNotification($newEmail, $fullName, $newEmail);

    echo json_encode([
        'success' => true,
        'message' => 'Email address successfully updated! You can now log in using your new email address.'
    ]);

} catch (Exception $e) {
    if ($pdo->inTransaction())
        $pdo->rollBack();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
