<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header("Access-Control-Allow-Methods: POST");
header("Allow: POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Allow-Origin");
require_once '../database.php'; // Adjust if needed

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

// Validate input
if (!isset($data['email']) || !isset($data['otp'])) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Missing email or OTP'
    ]);
    exit;
}

$email = trim($data['email']);
$otp = trim($data['otp']);

// Validate OTP format
if (!is_numeric($otp) || strlen($otp) !== 4) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid OTP format'
    ]);
    exit;
}

try {
    // Fetch the subscriber and verify OTP
    $stmt = $conn->prepare("SELECT sVerCode FROM subscribers WHERE sEmail = :email");
    $stmt->execute(['email' => $email]);
    
    if ($stmt->rowCount() === 0) {
        echo json_encode([
            'status' => 'error',
            'message' => 'Email not found'
        ]);
        exit;
    }
    
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Compare OTP only (NO updating or modifying)
    if ((int)$row['sVerCode'] === (int)$otp) {

        echo json_encode([
            'status' => 'success',
            'message' => 'OTP verified successfully'
        ]);

    } else {
        echo json_encode([
            'status' => 'error',
            'message' => 'Invalid OTP'
        ]);
    }

} catch (Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => 'An error occurred during verification'
    ]);
}
?>
