<?php
set_time_limit(300);
ini_set('memory_limit', '128M');
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/db_connect.php';
require_once __DIR__ . '/../includes/functions.php';

echo "<h1>Memulai Sinkronisasi Metode Deposit PayDisini</h1>";
echo "<pre>";

if (!isset($pdo) || !$pdo instanceof PDO) { die("FATAL ERROR: Koneksi database (\$pdo) tidak tersedia."); }
if (!defined('PAYDISINI_API_KEY') || empty(PAYDISINI_API_KEY)) { die("FATAL ERROR: PAYDISINI_API_KEY tidak didefinisikan di config.php."); }

$paydisiniApiKey = PAYDISINI_API_KEY;
$paydisiniApiUrl = 'https://api.paydisini.co.id/v1/';
$requestType = 'payment_channel';
$signature = md5($paydisiniApiKey . 'PaymentChannel');

$postData = [
    'key' => $paydisiniApiKey,
    'request' => $requestType,
    'signature' => $signature
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $paydisiniApiUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$apiResultJson = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);

if ($curlError || $httpCode !== 200) {
    echo "ERROR: Gagal menghubungi API PayDisini.\n";
    echo "HTTP Code: " . $httpCode . "\n";
    echo "cURL Error: " . $curlError . "\n";
    echo "Response: " . $apiResultJson . "\n";
    echo "</pre>";
    exit;
}

$apiResult = json_decode($apiResultJson, true);

if (json_last_error() !== JSON_ERROR_NONE || !isset($apiResult['success'])) {
    echo "ERROR: Respons API PayDisini tidak valid.\n";
    echo "Response: " . $apiResultJson . "\n";
    echo "</pre>";
    exit;
}

if ($apiResult['success'] === false) {
    echo "ERROR: API PayDisini mengembalikan status gagal.\n";
    echo "Pesan: " . ($apiResult['msg'] ?? 'Tidak ada pesan error spesifik.') . "\n";
    echo "</pre>";
    exit;
}

if (!isset($apiResult['data']) || !is_array($apiResult['data'])) {
    echo "ERROR: Data payment channel tidak ditemukan dalam respons API.\n";
    echo "Response: " . $apiResultJson . "\n";
    echo "</pre>";
    exit;
}

$apiChannels = $apiResult['data'];
echo "Berhasil mengambil " . count($apiChannels) . " payment channel dari PayDisini.\n\n";

$insertedCount = 0;
$updatedCount = 0;
$inactiveCount = 0;
$errorCount = 0;
$processedCodes = [];

try {
    $pdo->beginTransaction();

    $sqlSelect = "SELECT id, code, name, status FROM deposit_methods WHERE code = :code LIMIT 1";
    $sqlInsert = "INSERT INTO deposit_methods (name, code, type, logo_url, min_deposit, max_deposit, fee_amount, fee_percentage, bonus_percentage, is_auto_check, status, created_at, updated_at) VALUES (:name, :code, :type, :logo_url, :min_deposit, :max_deposit, :fee_amount, :fee_percentage, :bonus_percentage, :is_auto_check, :status, NOW(), NOW())";
    $sqlUpdate = "UPDATE deposit_methods SET name = :name, type = :type, logo_url = :logo_url, min_deposit = :min_deposit, max_deposit = :max_deposit, fee_amount = :fee_amount, fee_percentage = :fee_percentage, bonus_percentage = :bonus_percentage, is_auto_check = :is_auto_check, status = :status, updated_at = NOW() WHERE id = :id";

    $stmtSelect = $pdo->prepare($sqlSelect);
    $stmtInsert = $pdo->prepare($sqlInsert);
    $stmtUpdate = $pdo->prepare($sqlUpdate);

    foreach ($apiChannels as $channel) {
        $code = (string)$channel['id'];
        $processedCodes[] = $code;

        echo "Memproses Channel: {$channel['name']} (ID: {$code})... ";

        $localType = 'bank_transfer';
        $apiType = strtoupper($channel['type'] ?? '');
        if ($apiType === 'VA') { $localType = 'virtual_account'; }
        elseif ($apiType === 'EWALLET') { $localType = 'e_wallet'; }
        elseif ($apiType === 'QRIS') { $localType = 'e_wallet'; }
        elseif ($apiType === 'RETAIL') { $localType = 'retail_outlet'; }

        $localStatus = (strtoupper($channel['status'] ?? 'OFF') === 'ON') ? 'active' : 'inactive';

        $feeAmount = 0.00;
        $feePercentage = 0.00;
        $feeRaw = $channel['fee'] ?? 0;
        if (is_string($feeRaw) && strpos($feeRaw, '%') !== false) {
            $feePercentage = (float)str_replace('%', '', $feeRaw);
        } else {
            $feeAmount = (float)$feeRaw;
        }

        $name = $channel['name'] ?? 'Unknown';
        $logoUrl = $channel['img'] ?? null;
        $minDeposit = (float)($channel['minimum'] ?? 0);
        $maxDeposit = isset($channel['maximum']) ? (float)$channel['maximum'] : null;
        $isAutoCheck = 1;
        $bonusPercentage = 0.00;

        $stmtSelect->bindParam(':code', $code);
        $stmtSelect->execute();
        $existingMethod = $stmtSelect->fetch(PDO::FETCH_ASSOC);

        try {
            if ($existingMethod) {
                $stmtUpdate->bindParam(':name', $name);
                $stmtUpdate->bindParam(':type', $localType);
                $stmtUpdate->bindParam(':logo_url', $logoUrl);
                $stmtUpdate->bindParam(':min_deposit', $minDeposit);
                $stmtUpdate->bindParam(':max_deposit', $maxDeposit);
                $stmtUpdate->bindParam(':fee_amount', $feeAmount);
                $stmtUpdate->bindParam(':fee_percentage', $feePercentage);
                $stmtUpdate->bindParam(':bonus_percentage', $bonusPercentage);
                $stmtUpdate->bindParam(':is_auto_check', $isAutoCheck, PDO::PARAM_INT);
                $stmtUpdate->bindParam(':status', $localStatus);
                $stmtUpdate->bindParam(':id', $existingMethod['id'], PDO::PARAM_INT);
                $stmtUpdate->execute();
                echo "[UPDATED]\n";
                $updatedCount++;
            } else {
                $stmtInsert->bindParam(':name', $name);
                $stmtInsert->bindParam(':code', $code);
                $stmtInsert->bindParam(':type', $localType);
                $stmtInsert->bindParam(':logo_url', $logoUrl);
                $stmtInsert->bindParam(':min_deposit', $minDeposit);
                $stmtInsert->bindParam(':max_deposit', $maxDeposit);
                $stmtInsert->bindParam(':fee_amount', $feeAmount);
                $stmtInsert->bindParam(':fee_percentage', $feePercentage);
                $stmtInsert->bindParam(':bonus_percentage', $bonusPercentage);
                $stmtInsert->bindParam(':is_auto_check', $isAutoCheck, PDO::PARAM_INT);
                $stmtInsert->bindParam(':status', $localStatus);
                $stmtInsert->execute();
                echo "[INSERTED]\n";
                $insertedCount++;
            }
        } catch (\PDOException $e) {
            echo "[DB ERROR] " . $e->getMessage() . "\n";
            $errorCount++;
        }
    }

    if (!empty($processedCodes)) {
        $placeholders = implode(',', array_fill(0, count($processedCodes), '?'));
        $sqlDeactivate = "UPDATE deposit_methods SET status = 'inactive', updated_at = NOW() WHERE code NOT IN ({$placeholders})";
        $stmtDeactivate = $pdo->prepare($sqlDeactivate);
        foreach ($processedCodes as $k => $pCode) {
            $stmtDeactivate->bindValue(($k + 1), $pCode);
        }
        $stmtDeactivate->execute();
        $inactiveCount = $stmtDeactivate->rowCount();
        echo "\nMenonaktifkan {$inactiveCount} metode lokal yang tidak ditemukan di API.\n";
    }

    $pdo->commit();

    echo "\n=====================================\n";
    echo "Sinkronisasi Metode Deposit Selesai!\n";
    echo "=====================================\n";
    echo "Metode Baru Ditambahkan: {$insertedCount}\n";
    echo "Metode Diperbarui: {$updatedCount}\n";
    echo "Metode Dinonaktifkan: {$inactiveCount}\n";
    echo "Error Pemrosesan: {$errorCount}\n";

} catch (\PDOException $e) {
    if ($pdo->inTransaction()) { $pdo->rollBack(); }
    echo "\n=====================================\n";
    echo "ERROR DATABASE UTAMA!\n";
    echo "=====================================\n";
    echo "Pesan Error: " . $e->getMessage() . "\n";
    error_log("Cron Sync Deposit Methods PDO Exception: " . $e->getMessage());
} catch (\Throwable $e) {
     if ($pdo->inTransaction()) { $pdo->rollBack(); }
     echo "\n=====================================\n";
    echo "ERROR UMUM!\n";
    echo "=====================================\n";
    echo "Pesan Error: " . $e->getMessage() . "\n";
    error_log("Cron Sync Deposit Methods General Error: " . $e->getMessage());
}

echo "</pre>";
?>
