<?php
session_start();
require 'includes/config.php';
require 'includes/send_otp.php';

/* ===============================
   RESEND OTP
================================ */
if (isset($_GET['resend']) && $_GET['resend'] === 'true' && isset($_SESSION['temp_admin_id'])) {
    $adminId = $_SESSION['temp_admin_id'];

    $stmt = $pdo->prepare("SELECT phone_number FROM admin_account WHERE id = ?");
    $stmt->execute([$adminId]);
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$admin) {
        header("Location: login.php?error=session");
        exit;
    }

    $otp = random_int(100000, 999999);
    $expiry = date("Y-m-d H:i:s", strtotime("+5 minutes"));

    $update = $pdo->prepare("UPDATE admin_account SET otp_code = ?, otp_expiry = ? WHERE id = ?");

    if ($update->execute([$otp, $expiry, $adminId])) {
        sendWhatsAppOTP($admin['phone_number'], $otp);
        header("Location: verify_otp.php?resent=1");
        exit;
    }

    header("Location: verify_otp.php?error=otp");
    exit;
}

/* ===============================
   LOGIN & OTP GENERATION
================================ */
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $user = trim($_POST['username'] ?? '');
    $pass = $_POST['password'] ?? '';
    $recaptchaResponse = $_POST['g-recaptcha-response'] ?? '';

    if ($user === '' || $pass === '') {
        header("Location: login.php?error=empty");
        exit;
    }

    // Google reCAPTCHA Verification
    $secretKey = "6LduzUYsAAAAAMTO2SSvOaXCc5954yPsPt1-PDlO";
    $ch = curl_init("https://www.google.com/recaptcha/api/siteverify");
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS => http_build_query([
            'secret' => $secretKey,
            'response' => $recaptchaResponse
        ])
    ]);

    $response = json_decode(curl_exec($ch), true);
    curl_close($ch);

    if (empty($response['success'])) {
        header("Location: login.php?error=captcha");
        exit;
    }

    // Admin Verification
    $stmt = $pdo->prepare("SELECT * FROM admin_account WHERE username = ?");
    $stmt->execute([$user]);
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$admin || !password_verify($pass, $admin['password'])) {
        header("Location: login.php?error=invalid");
        exit;
    }

    // Generate OTP
    $otp = random_int(100000, 999999);
    $expiry = date("Y-m-d H:i:s", strtotime("+5 minutes"));

    $update = $pdo->prepare("UPDATE admin_account SET otp_code = ?, otp_expiry = ? WHERE id = ?");

    if ($update->execute([$otp, $expiry, $admin['id']])) {
        $_SESSION['temp_admin_id'] = $admin['id'];
        $result=sendWhatsAppOTP($admin['phone_number'], $otp);
       // Debug output
echo "<pre>";
print_r($result);
echo "</pre>";
exit;


        header("Location: verify_otp.php"); // Moved inside the success block
        exit;
    } else {
        header("Location: login.php?error=db");
        exit;
    }
}
// No closing PHP tag to prevent "headers already sent" errors