<?php
// Your Public API Endpoint for Resellers (Final Corrected Version)
require 'config.php';
header('Content-Type: application/json');

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

// --- 1. RECEIVE AND VALIDATE THE RESELLER'S REQUEST ---
$reseller_key = $_GET['key'] ?? '';
$nid = trim($_GET['nid'] ?? '');
$dob = trim($_GET['dob'] ?? '');
$service_type = 'server_copy';

if (empty($reseller_key) || empty($nid) || empty($dob)) {
    sendError("Missing required parameters.");
}

try {
    // --- 2. VALIDATE THE RESELLER AND THEIR BALANCE ---
    $stmt = $pdo->prepare("SELECT * FROM resellers WHERE api_key = ?");
    $stmt->execute([$reseller_key]);
    $reseller = $stmt->fetch();
    if (!$reseller) { sendError("Invalid API key."); }
    if (!$reseller['is_active']) { sendError("Your reseller account is inactive."); }
    $reseller_cost = (float)($settings['reseller_server_copy_cost'] ?? 30);
    if ($reseller['balance'] < $reseller_cost) {
        sendError("Insufficient balance in your reseller account.");
    }

    // --- 3. START TRANSACTION, LOG, AND DEDUCT BALANCE ---
    $pdo->beginTransaction();
    $new_balance = $reseller['balance'] - $reseller_cost;
    $stmt = $pdo->prepare("UPDATE resellers SET balance = ? WHERE id = ?");
    $stmt->execute([$new_balance, $reseller['id']]);
    $request_details = "NID: $nid, DOB: $dob";
    $stmt = $pdo->prepare("INSERT INTO api_logs (reseller_id, service_requested, request_details, cost, status) VALUES (?, ?, ?, ?, 'pending')");
    $stmt->execute([$reseller['id'], $service_type, $request_details, $reseller_cost]);
    $log_id = $pdo->lastInsertId();

    // --- 4. SECRETLY CALL THE MAIN API PROVIDER ---
    $main_api_key = $settings['sc_api1_key'] ?? '';
    $main_api_url = $settings['sc_api1_url'] ?? '';
    if (empty($main_api_url) || empty($main_api_key)) {
        throw new Exception("Main API provider is not configured.");
    }
    $full_api_url = "$main_api_url?key=$main_api_key&nid=$nid&dob=$dob";
    
    $ch = curl_init($full_api_url);
    
    // --- THIS IS THE FINAL FIX ---
    // Added a User-Agent header to mimic a real browser request.
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false, // Keep this for safety on shared hosting
        CURLOPT_TIMEOUT        => 40,
        CURLOPT_HTTPHEADER     => [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36'
        ]
    ]);
    // --- END OF FIX ---
    
    $response = curl_exec($ch);
    curl_close($ch);
    $api_data = json_decode($response, true);

    // --- 5. PROCESS THE RESPONSE ---
    if ($api_data && isset($api_data['nameBangla']) && !empty($api_data['nameBangla'])) {
        // SUCCESS
        $stmt = $pdo->prepare("UPDATE api_logs SET status = 'success', response = ? WHERE id = ?");
        $stmt->execute([$response, $log_id]);
        $pdo->commit();
        echo $response;
    } else {
        // FAILURE
        throw new Exception($api_data['message'] ?? 'Information not found from the main provider.');
    }

} catch (Throwable $e) {
    if ($pdo->inTransaction()) { $pdo->rollBack(); }
    if (isset($log_id)) {
        $stmt = $pdo->prepare("UPDATE api_logs SET status = 'failed', response = ? WHERE id = ?");
        $stmt->execute([$e->getMessage(), $log_id]);
    }
    sendError($e->getMessage());
}
?>