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

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

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

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

$identity = trim($data['nroi_id'] ?? ''); // This can be NROI ID or Username
$email = trim($data['email'] ?? '');

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

try {
    // 1. Check if user exists (Regular user/Officer)
    $stmt = $pdo->prepare("SELECT id, first_name, last_name FROM users WHERE nroi_id = ? AND email = ?");
    $stmt->execute([$identity, $email]);
    $user = $stmt->fetch();

    $userType = 'regular';
    $targetId = null;
    $fullName = '';

    if ($user) {
        $targetId = $user['id'];
        $fullName = ($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '');
    } else {
        // 2. Check if admin exists
        $stmtAdmin = $pdo->prepare("SELECT id, first_name, last_name, username FROM admins WHERE username = ? AND email = ?");
        $stmtAdmin->execute([$identity, $email]);
        $admin = $stmtAdmin->fetch();

        if ($admin) {
            $userType = 'admin';
            $targetId = $admin['id'];
            $fullName = trim(($admin['first_name'] ?? '') . ' ' . ($admin['last_name'] ?? ''));
            if (empty($fullName))
                $fullName = $admin['username'];
        }
    }

    if (!$targetId) {
        echo json_encode(['success' => false, 'message' => 'No account found with this Identity and Email combination.']);
        exit;
    }

    // 3. Generate 6-digit OTP
    $otp = sprintf("%06d", mt_rand(1, 999999));
    $expiresAt = date('Y-m-d H:i:s', strtotime('+10 minutes'));

    // 4. Save OTP to database
    if ($userType === 'admin') {
        $pdo->prepare("DELETE FROM admin_password_resets WHERE admin_id = ?")->execute([$targetId]);
        $stmtInsert = $pdo->prepare("INSERT INTO admin_password_resets (admin_id, email, otp, expires_at) VALUES (?, ?, ?, ?)");
        $stmtInsert->execute([$targetId, $email, $otp, $expiresAt]);
    } else {
        $pdo->prepare("DELETE FROM password_resets WHERE user_id = ?")->execute([$targetId]);
        $stmtInsert = $pdo->prepare("INSERT INTO password_resets (user_id, email, otp, expires_at) VALUES (?, ?, ?, ?)");
        $stmtInsert->execute([$targetId, $email, $otp, $expiresAt]);
    }

    // 5. Send Email
    $emailSent = sendOTP($email, $fullName, $otp);

    if ($emailSent) {
        echo json_encode([
            'success' => true,
            'message' => 'OTP has been sent to your email.',
            'expires_at' => $expiresAt,
            'user_type' => $userType // Optional: helps the verify/reset API know where to look if we pass it back
        ]);
    } else {
        throw new Exception("Failed to send OTP email. Please try again later.");
    }

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