<?php
require_once '../config/headers.php';
require_once '../config/database.php';
require_once '../utils/response.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(405, 'error', 'Method not allowed');
}

$data = json_decode(file_get_contents("php://input"));

if (empty($data->email) || empty($data->otp)) {
    sendResponse(400, 'error', 'Email and OTP are required');
}

$database = new Database();
$db = $database->getConnection();

try {
    // Find admin by email and check OTP
    $stmt = $db->prepare("SELECT id, otp_expires_at FROM admins WHERE email = :email AND reset_otp = :otp LIMIT 1");
    $stmt->execute(['email' => $data->email, 'otp' => $data->otp]);
    
    if ($stmt->rowCount() > 0) {
        $admin = $stmt->fetch();
        
        // Check if OTP is expired
        if (strtotime($admin['otp_expires_at']) < time()) {
            sendResponse(400, 'error', 'OTP has expired. Please request a new one.');
        }

        sendResponse(200, 'success', 'OTP verified successfully');
    } else {
        sendResponse(400, 'error', 'Invalid OTP');
    }
} catch (PDOException $e) {
    sendResponse(500, 'error', 'Database error occurred');
}
?>