<?php
// api/send_otp.php
// Handles the request to generate and send an OTP, with logic for both
// first-time (unverified, long OTP) and regular (verified, 6-digit OTP) logins.

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

// 1. Configuration & Setup
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

require_once '../config/database.php';
require_once '../vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

function json_response($success, $message, $data = []) {
    echo json_encode(['success' => $success, 'message' => $message, 'data' => $data]);
    exit();
}

// --- EMAIL SENDING FUNCTION for Login OTP ---
/**
 * Sends the verification code email.
 * Includes error reporting via the $error_info reference parameter.
 */
function sendLoginOtpEmail(PHPMailer $mail, string $recipient_email, string $recipient_name, string $otp_code, bool $is_first_login, &$error_info): bool {
    try {
        // 🚨 CRITICAL: CONFIGURE YOUR SMTP SETTINGS HERE 🚨
        $mail->isSMTP();
        // $mail->SMTPDebug  = 2; // Uncomment for verbose debugging output to the server logs/AJAX response
        $mail->Host       = 'smtp.gmail.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'bazithali95@gmail.com';
        $mail->Password   = 'sqkt opow cvao fiac'; // VERIFY THIS IS THE CORRECT APP PASSWORD
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;
        
        $mail->setFrom('bazithali95@gmail.com', 'Orinsto LMS');
        $mail->addAddress($recipient_email, $recipient_name);
        $mail->isHTML(true);

        if ($is_first_login) {
            $subject = 'Welcome to Orinsto LMS - Your First Login Verification Code';
            $body = "
                <p>Welcome to Orinsto LMS! Your account was recently created by an administrator.</p>
                <p>Please use this **one-time verification code** to verify your account and set your permanent password.</p>
                <p style='font-size: 24px; font-weight: bold; text-align: center; color: #007bff; background-color: #f0f8ff; padding: 20px; border-radius: 5px;'>{$otp_code}</p>
                <p>This code is the one sent at registration and is valid until its original expiry time.</p>";
        } else {
            // SCENARIO 2: Regular 6-digit OTP for verified users
            $subject = 'LMS Login One-Time Code: ' . $otp_code;
            $body = "
                <p>You have requested a One-Time Password (OTP) to log in.</p>
                <div style='text-align: center; margin: 25px 0; padding: 15px; background-color: #f4f4f4; border-radius: 5px; border: 1px dashed #ccc;'>
                    <p style='font-size: 14px; margin: 0;'>Your 6-digit OTP Code is:</p>
                    <p style='font-size: 32px; font-weight: bold; color: #dc3545; margin: 5px 0;'>{$otp_code}</p>
                </div>
                <p>This code is valid for 5 minutes. Do not share it.</p>";
        }

        $mail->Subject = $subject;
        $mail->Body    = $body;
        $mail->AltBody = "Your verification code is: {$otp_code}.";

        return $mail->send();

    } catch (Exception $e) {
        // Capture the specific error from PHPMailer and log it
        $error_info = $mail->ErrorInfo;
        error_log("OTP Email failed: " . $error_info);
        return false;
    }
}
// --- END EMAIL SENDING FUNCTION ---

// 2. Input Validation and Sanitization
$input = json_decode(file_get_contents('php://input'), true);
$identifier = trim($input['identifier'] ?? '');

if (empty($identifier)) {
    json_response(false, 'Username or Email is required.');
}

// 3. Find User and Check Status
try {
    $sql = "SELECT id, email, full_name, role, verified, otp, otp_expiry FROM users WHERE username = ? OR email = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$identifier, $identifier]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        // Generic success message for security
        json_response(true, 'If an account exists, a code has been sent to the associated email address.');
    }

    $user_id = $user['id'];
    $recipient_email = $user['email'];
    $recipient_name = $user['full_name'] ?? 'User';
    $is_verified = $user['verified'] == 1; 
    $is_first_login = !$is_verified;

} catch (PDOException $e) {
    error_log("Database Error finding user: " . $e->getMessage());
    json_response(false, 'A database error occurred during user lookup.');
}

// 4. Conditional OTP Generation and Storage
$otp_code = '';
$mail = new PHPMailer(true);

try {
    if ($is_first_login) {
        // SCENARIO 1: FIRST-TIME LOGIN (Unverified User)
        if (empty($user['otp']) || strtotime($user['otp_expiry']) < time()) {
            json_response(false, 'Your initial verification code has expired. Please contact your administrator.');
        }
        $otp_code = $user['otp']; // Use the long, existing OTP

    } else {
        // SCENARIO 2: REGULAR LOGIN (Verified User) - Generates new 6-digit OTP
        $otp_code = random_int(100000, 999999); 
        $expiry_minutes = 5;
        $expires_at = date('Y-m-d H:i:s', strtotime("+$expiry_minutes minutes"));

        // Clean up old OTPs and insert new one into the `otp_codes` table
        $sql_delete = "DELETE FROM otp_codes WHERE user_id = ?";
        $pdo->prepare($sql_delete)->execute([$user_id]);
        $sql_insert = "INSERT INTO otp_codes (user_id, otp_code, expires_at) VALUES (?, ?, ?)";
        $pdo->prepare($sql_insert)->execute([$user_id, $otp_code, $expires_at]);
    }
    
    // 5. Send OTP Email and get error info if it fails
    $mailer_error = '';
    if (sendLoginOtpEmail($mail, $recipient_email, $recipient_name, $otp_code, $is_first_login, $mailer_error)) {
        
        $message = $is_first_login 
            ? "Your initial verification code has been re-sent to {$recipient_email}."
            : "A new 6-digit OTP has been sent to {$recipient_email}.";
            
        // Return the is_first_login flag for the frontend to adjust the input field
        json_response(true, $message, ['user_id' => $user_id, 'is_first_login' => $is_first_login]);
    } else {
        // ❌ FAILURE BLOCK - Return the specific Mailer error to the frontend
        json_response(false, 'Failed to send verification email. Please try again. Error: ' . $mailer_error);
    }

} catch (PDOException $e) {
    error_log("Database Error: " . $e->getMessage());
    json_response(false, 'A database error occurred.');
} catch (Exception $e) {
    error_log("Error during OTP processing: " . $e->getMessage());
    json_response(false, 'An unexpected error occurred on the server.');
}