<?php
// api/verify_otp.php
// Verifies the provided OTP and handles persistent login.

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

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

require_once '../config/database.php';
require_once '../includes/auth_utils.php'; // Include utility functions

$input = json_decode(file_get_contents('php://input'), true);
$identifier = trim($input['identifier'] ?? '');
$otp_code = trim($input['otp'] ?? '');
$remember_device = (bool)($input['remember_device'] ?? false);

$response = ['success' => false, 'message' => ''];

if (empty($identifier) || empty($otp_code)) {
    $response['message'] = "Identifier and verification code are required.";
    echo json_encode($response);
    exit();
}

try {
    $pdo->beginTransaction();

    // 1. Find User and their verification status
    $field = filter_var($identifier, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
    $sql_user = "SELECT id, username, email, full_name, role, verified FROM users WHERE {$field} = ?";
    $stmt_user = $pdo->prepare($sql_user);
    $stmt_user->execute([$identifier]);
    $user = $stmt_user->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        $response['message'] = "Invalid identifier or verification code.";
        echo json_encode($response);
        exit();
    }
    
    $user_id = $user['id'];
    $is_verified_user = $user['verified'] == 1;
    $is_otp_valid = false;
    $redirect_url = 'index.php?page=home';

    // 2. Conditional OTP Verification based on User Status
    // --- SCENARIO 1: FIRST-TIME LOGIN (UNVERIFIED USER - Uses long OTP from users table) ---
    if (!$is_verified_user) {
        $sql_first_login_otp = "SELECT otp, otp_expiry FROM users WHERE id = ?";
        $stmt_first_login = $pdo->prepare($sql_first_login_otp);
        $stmt_first_login->execute([$user_id]);
        $first_login_data = $stmt_first_login->fetch(PDO::FETCH_ASSOC);

        if ($first_login_data && $first_login_data['otp'] === $otp_code && strtotime($first_login_data['otp_expiry']) > time()) {
            $is_otp_valid = true;
            
            // Mark the user as verified and clear the one-time OTP
            $sql_update_user = "UPDATE users SET verified = 1, otp = NULL, otp_expiry = NULL WHERE id = ?";
            $pdo->prepare($sql_update_user)->execute([$user_id]);
            
            $redirect_url = 'index.php?page=set_new_password'; 
        }

    // --- SCENARIO 2: REGULAR LOGIN (VERIFIED USER - Uses short OTP from otp_codes table) ---
    } else { 
        $sql_otp = "SELECT expires_at FROM otp_codes WHERE user_id = ? AND otp_code = ? AND expires_at > NOW()";
        $stmt_otp = $pdo->prepare($sql_otp);
        $stmt_otp->execute([$user_id, $otp_code]);
        $otp_record = $stmt_otp->fetch(PDO::FETCH_ASSOC);

        if ($otp_record) {
            $is_otp_valid = true;
            
            // Delete the used OTP to prevent replay attacks
            $sql_delete_otp = "DELETE FROM otp_codes WHERE user_id = ? AND otp_code = ?";
            $pdo->prepare($sql_delete_otp)->execute([$user_id, $otp_code]);
            
            $role_redirect_map = [
                'student' => 'index.php?page=student_dashboard',
                'admin' => 'index.php?page=admin_landing',
                'instructor' => 'index.php?page=admin_landing',
            ];
            $redirect_url = $role_redirect_map[$user['role']] ?? 'index.php?page=home';
        }
    }

    // 3. Finalize Login and Persistent Token Setup
    if ($is_otp_valid) {
        // Log the user in to the SESSION
        $_SESSION['loggedin'] = true;
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['full_name'] = $user['full_name'];
        $_SESSION['user_role'] = $user['role'];

        // --- PERSISTENT LOGIN CREATION (Only for verified users who opted in) ---
        if ($is_verified_user && $remember_device) {
            $selector = generate_secure_token(16);
            $validator = generate_secure_token(32);
            $validator_hash = hash('sha256', $validator);
            $expiry_timestamp = time() + (86400 * 7); 
            $expires_at = date('Y-m-d H:i:s', $expiry_timestamp);
            $full_token = $selector . ':' . $validator;
            $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';

            // Store token in DB and set cookie
            $sql_insert_token = "INSERT INTO user_devices (user_id, selector, validator_hash, expires_at, user_agent) 
                                 VALUES (?, ?, ?, ?, ?)";
            $pdo->prepare($sql_insert_token)->execute([$user_id, $selector, $validator_hash, $expires_at, $user_agent]);
            set_persistent_cookie($full_token, $expiry_timestamp);
        }

        $pdo->commit();
        $response['success'] = true;
        $response['message'] = "Verification successful! Redirecting...";
        $response['redirect'] = $redirect_url;

    } else {
        $pdo->rollBack();
        $response['message'] = "Invalid or expired verification code. Please try again.";
    }

} catch (PDOException $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    $response['message'] = "A database error occurred during verification.";
    error_log("Verify OTP PDOException: " . $e->getMessage());
} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    $response['message'] = "An unexpected server error occurred.";
    error_log("Verify OTP Exception: " . $e->getMessage());
}

echo json_encode($response);
exit();