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

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

session_start();

$userId = $_SESSION['user_id'] ?? null;
$userType = $_SESSION['user_type'] ?? 'regular'; // Default to regular if not set, but usually set at login

// For mobile app, it might send user_id via POST if session is not used
if (!$userId) {
    $json = file_get_contents('php://input');
    $data = json_decode($json, true);
    $userId = $data['user_id'] ?? null;
    $userType = $data['user_type'] ?? 'regular';
}

if (!$userId) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized. Please log in.']);
    exit;
}

try {
    // 1. Get user details
    if ($userType === 'admin') {
        $stmt = $pdo->prepare("SELECT id, username, first_name, last_name, email FROM admins WHERE id = ?");
        $stmt->execute([$userId]);
        $user = $stmt->fetch();
        $fullName = trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''));
        if (empty($fullName))
            $fullName = $user['username'] ?? 'Admin';
    } else {
        $stmt = $pdo->prepare("SELECT id, nroi_id, first_name, last_name, email FROM users WHERE id = ?");
        $stmt->execute([$userId]);
        $user = $stmt->fetch();
        $fullName = trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''));
        if (empty($fullName))
            $fullName = $user['nroi_id'] ?? 'User';
    }

    if (!$user || empty($user['email'])) {
        echo json_encode(['success' => false, 'message' => 'User or current email not found.']);
        exit;
    }

    $oldEmail = $user['email'];

    // 2. Generate token
    $token = bin2hex(random_bytes(32));
    $expiresAt = date('Y-m-d H:i:s', strtotime('+30 minutes'));

    // 3. Ensure table exists (just in case)
    $pdo->exec("CREATE TABLE IF NOT EXISTS email_change_requests (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        user_type ENUM('regular', 'admin') NOT NULL,
        old_email VARCHAR(255) NOT NULL,
        token VARCHAR(100) NOT NULL UNIQUE,
        expires_at DATETIME NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");

    // 4. Save to DB
    $stmtDelete = $pdo->prepare("DELETE FROM email_change_requests WHERE user_id = ? AND user_type = ?");
    $stmtDelete->execute([$userId, $userType]);

    $stmtInsert = $pdo->prepare("INSERT INTO email_change_requests (user_id, user_type, old_email, token, expires_at) VALUES (?, ?, ?, ?, ?)");
    $stmtInsert->execute([$userId, $userType, $oldEmail, $token, $expiresAt]);

    // 5. Send Email
    $emailSent = sendEmailChangeRequest($oldEmail, $fullName, $token);

    if ($emailSent) {
        echo json_encode([
            'success' => true,
            'message' => 'A confirmation email has been sent to ' . substr($oldEmail, 0, 3) . '****' . substr($oldEmail, strpos($oldEmail, '@')) . '. Please check your inbox and click the button to continue.'
        ]);
    } else {
        throw new Exception("Failed to send confirmation email. Please try again later.");
    }

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