<?php
session_start();
require_once '../config/db.php';
require_once '../includes/EmailSender.php';

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

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized Access']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Method Not Allowed']);
    exit;
}

$rank = trim($_POST['rank'] ?? ''); // NROI or PPSA
$email = trim($_POST['email'] ?? '');

if (empty($rank) || empty($email)) {
    echo json_encode(['success' => false, 'message' => 'Rank and Email are required.']);
    exit;
}

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

try {
    // 1. Check if email exists
    $stmtEmail = $pdo->prepare("SELECT id FROM users WHERE email = ?");
    $stmtEmail->execute([$email]);
    if ($stmtEmail->fetch()) {
        echo json_encode(['success' => false, 'message' => 'Email address already registered.']);
        exit;
    }

    // 2. Generate Unique Username
    $emailPrefix = explode('@', $email)[0];
    $emailPrefix = preg_replace('/[^a-zA-Z0-9]/', '', $emailPrefix);
    $isUnique = false;
    $username = '';

    while (!$isUnique) {
        $tempUsername = $emailPrefix . rand(100, 999);
        $stmtCheck = $pdo->prepare("SELECT id FROM users WHERE username = ?");
        $stmtCheck->execute([$tempUsername]);
        if (!$stmtCheck->fetch()) {
            $username = $tempUsername;
            $isUnique = true;
        }
    }

    // 3. Generate Random Password
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $password = substr(str_shuffle($chars), 0, 10);

    // 4. Set Profile Photo based on Rank
    // User requested: "NROI user, then profile pic is their logo. ppsa user, then profile pic is their logo"
    $profilePhoto = '';
    if (strtoupper($rank) === 'NROI') {
        $profilePhoto = 'assets/images/nroi_logo.png';
    } elseif (strtoupper($rank) === 'PPSA') {
        $profilePhoto = 'assets/images/ppsa_logo.png';
    }

    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
    $token = bin2hex(random_bytes(32));

    // 5. Create User (Status 'pending' until activation)
    $stmtInsert = $pdo->prepare("
        INSERT INTO users (
            username, email, password, role, rank, status, 
            is_email_confirmed, email_confirmation_token, is_first_login, 
            profile_photo, created_at, 
            first_name, last_name, gender, dob, phone_number
        ) VALUES (
            ?, ?, ?, ?, ?, 'pending', 
            0, ?, 1, 
            ?, NOW(), 
            '', '', 'Other', '1970-01-01', ''
        )
    ");

    $stmtInsert->execute([
        $username,
        $email,
        $hashedPassword,
        $rank,
        $rank,
        $token,
        $profilePhoto
    ]);

    // 6. Send Activation Email
    if (sendAccountActivation($email, $username, $username, $password, $token)) {
        echo json_encode([
            'success' => true,
            'message' => "Account created successfully!\n\nUsername: $username\nPassword: $password\n\nAn activation link has been sent to $email",
            'username' => $username,
            'password' => $password
        ]);
    } else {
        echo json_encode([
            'success' => true,
            'message' => "Account created successfully (User: $username), but activation email failed to send.",
            'username' => $username,
            'password' => $password
        ]);
    }

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
