<?php

session_start();

// 2. Set headers
header('Content-Type: application/json');

// 3. Include dependencies
require("../../includes/config.php");
require('../../includes/sendEmailOTP.php');

$response = ['status' => 'error', 'message' => 'An unknown error occurred'];

try {
    // Check if the database connection ($pdo) exists
    if (!isset($pdo)) {
        throw new Exception("Database connection failed.");
    }

    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    $captcha = $_POST['g-recaptcha-response'] ?? '';

    if (empty($username) || empty($password) || empty($captcha)) {
        throw new Exception('Please fill in all fields and verify the captcha.');
    }

    // --- reCAPTCHA Verify ---
    $secret = "6LduzUYsAAAAAMTO2SSvOaXCc5954yPsPt1-PDlO";
    $captchaResponse = $_POST['g-recaptcha-response'] ?? '';

    if (empty($captchaResponse)) {
        throw new Exception('Please complete the reCAPTCHA.');
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'secret' => $secret,
        'response' => $captcha,
        'remoteip' => $_SERVER['REMOTE_ADDR']
    ]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $verifyResponse = curl_exec($ch);
    $captchaData = json_decode($verifyResponse);

    if (!$captchaData || !$captchaData->success) {
        throw new Exception('Captcha verification failed.');
    }

    // --- Database Check ---
    $stmt = $pdo->prepare("SELECT id, username, password, email FROM admin_account WHERE username = ? LIMIT 1");
    $stmt->execute([$username]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user && password_verify($password, $user['password'])) {

        // 1. Generate 6-digit OTP
        $otp = (string) rand(100000, 999999);

        // 2. Store in Session
        $_SESSION['temp_admin_id'] = $user['id'];
        $_SESSION['pending_otp'] = $otp;
        $_SESSION['otp_expiry'] = time() + (10 * 60);

        // 3. Send Email
        $emailStatus = sendEmailOTP($user['email'], $otp);

        if ($emailStatus === true) {
            $response = [
                'status' => 'pending',
                'message' => 'Credentials verified. Please check your email for OTP.'
            ];
        } else {
            // If email fails, we tell the user why
            throw new Exception("Logged in, but email failed: " . $emailStatus);
        }

    } else {
        throw new Exception('Invalid username or password.');
    }

} catch (Exception $e) {
    $response = ['status' => 'error', 'message' => $e->getMessage()];
}

// 4. Clean the buffer and send pure JSON
ob_end_clean();
echo json_encode($response);
exit; ?>