<?php
require_once 'config/database.php';
require_once 'includes/zashof.php';

echo "Testing Zashof API Direct Connection:\n";
echo "=====================================\n";

try {
    // Get the Zashof configuration directly from database
    $stmt = $pdo->query("SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE 'zashof_%'");
    $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    
    $api_key = $settings['zashof_api_key'] ?? '';
    $base_url = $settings['zashof_base_url'] ?? '';
    $create_charge_url = $settings['zashof_create_charge_url'] ?? '';
    
    echo "API Key: " . (strlen($api_key) > 20 ? substr($api_key, 0, 10) . '...' . substr($api_key, -10) : $api_key) . "\n";
    echo "Base URL: " . $base_url . "\n";
    echo "Create Charge URL: " . $create_charge_url . "\n";
    echo "API Key Length: " . strlen($api_key) . " characters\n";
    
    // Test direct API call
    echo "\nTesting Direct API Call:\n";
    
    $data = [
        'amount' => 100,
        'currency' => 'BDT',
        'redirect_url' => 'http://localhost/fees/zashof_success.php',
        'cancel_url' => 'http://localhost/fees/my_fees.php',
        'client_name' => 'Test Student',
        'client_email' => 'test@example.com',
        'client_mobile' => '01712345678',
        'student_id' => '12345',
        'description' => 'Test Payment',
        'metadata' => [
            'student_id' => '12345',
            'student_name' => 'Test Student',
            'payment_for' => 'test'
        ]
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $create_charge_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key,
        'Accept: application/json'
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Bidda School Management System/1.0');
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    echo "HTTP Response Code: " . $httpCode . "\n";
    echo "cURL Error: " . ($error ?: "None") . "\n";
    echo "Response: " . $response . "\n";
    
    if ($httpCode === 401) {
        echo "ERROR: Unauthorized - Invalid API Key\n";
        echo "Please check if the API key is correct and has proper permissions\n";
    } elseif ($httpCode === 200 || $httpCode === 201) {
        echo "SUCCESS: API Key is valid and working\n";
    } else {
        echo "OTHER ERROR: HTTP " . $httpCode . "\n";
    }
    
} catch (Exception $e) {
    echo "Exception: " . $e->getMessage() . "\n";
}
?>