<?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);

if (!$data) {
    $data = $_POST;
}

$userId = trim($data['user_id'] ?? '');
$userType = trim($data['user_type'] ?? 'regular'); // 'regular' or 'admin'
$currentPassword = trim($data['current_password'] ?? '');

if (empty($userId) || empty($currentPassword)) {
    echo json_encode(['success' => false, 'message' => 'User ID and Current Password are required.']);
    exit;
}

try {
    if ($userType === 'admin') {
        $stmt = $pdo->prepare("SELECT id, username, first_name, last_name, email, password FROM admins WHERE id = ?");
        $stmt->execute([$userId]);
        $user = $stmt->fetch();
        $identity = $user['username'] ?? '';
    } else {
        $stmt = $pdo->prepare("SELECT id, nroi_id, first_name, last_name, email, password FROM users WHERE id = ?");
        $stmt->execute([$userId]);
        $user = $stmt->fetch();
        $identity = $user['nroi_id'] ?? '';
    }

    if (!$user) {
        echo json_encode(['success' => false, 'message' => 'Account not found.']);
        exit;
    }

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

    $email = $user['email'];
    if (empty($email)) {
        echo json_encode(['success' => false, 'message' => 'No email address associated with this account. Please update your profile first.']);
        exit;
    }

    // Generate 6-digit OTP
    $otp = sprintf("%06d", mt_rand(1, 999999));
    $expiresAt = date('Y-m-d H:i:s', strtotime('+10 minutes'));
    $fullName = trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''));
    if (empty($fullName)) {
        $fullName = $identity;
    }

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

    // 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,
            'identity' => $identity,
            'email_obscured' => substr($email, 0, 3) . '****' . substr($email, strpos($email, '@'))
        ]);
    } else {
        throw new Exception("Failed to send OTP email. Please try again later.");
    }

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