<?php
/**
 * Cron Job / Manual Script - Get AND INSERT Unique Categories from Provider API
 *
 * Mengambil data layanan dari API provider, mengidentifikasi kategori unik,
 * dan memasukkan kategori yang belum ada ke tabel 'categories' lokal.
 *
 * TODO: Amankan akses ke script ini di lingkungan produksi!
 */

set_time_limit(300);
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';

$providerId = 1;

echo "<h1>Memulai Pengambilan & Penyimpanan Kategori dari Provider ID: {$providerId}</h1>";
echo "<pre>";

if (!isset($pdo) || !$pdo instanceof PDO) {
    die("FATAL ERROR: Koneksi database (\$pdo) tidak tersedia. Periksa db_connect.php dan log error.");
}

try {
    $stmtProvider = $pdo->prepare("SELECT api_url, api_id, api_key, secret_key FROM providers WHERE id = :pid AND status = 'active'");
    $stmtProvider->bindParam(':pid', $providerId, PDO::PARAM_INT);
    $stmtProvider->execute();
    $provider = $stmtProvider->fetch(PDO::FETCH_ASSOC);
    if (!$provider) { die("Error: Provider ID {$providerId} tidak ditemukan/aktif."); }

    $apiServiceUrl = $provider['api_url']."services";
    if (empty($apiServiceUrl) || !filter_var($apiServiceUrl, FILTER_VALIDATE_URL) || strpos($apiServiceUrl, 'services') === false) {
         die("Error: URL API Provider (ID: {$providerId}) di database tidak valid atau bukan endpoint services.");
    }
    echo "Provider Ditemukan: Menggunakan API URL: " . htmlspecialchars($apiServiceUrl) . "\n";

} catch (\PDOException $e) { die("Error DB saat ambil provider: " . $e->getMessage()); }

$apiUrl = $apiServiceUrl;
$postData = [
    'api_id'     => $provider['api_id'],
    'api_key'    => $provider['api_key'],
    'secret_key' => $provider['secret_key'],
];

echo "Mengirim request ke API...\n";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
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, 120);
$apiResultJson = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);

if ($curlError) { die("Error cURL: " . $curlError); }
if ($httpCode !== 200) { echo "API HTTP Status: " . $httpCode . "\n"; /* ... */ die("Gagal menghubungi API provider."); }

echo "Respons API diterima (HTTP {$httpCode}). Mencoba decode JSON...\n";
$apiResult = json_decode($apiResultJson, true);
if (json_last_error() !== JSON_ERROR_NONE) { /* ... */ die("Error decode JSON."); }

if (!isset($apiResult['response']) || $apiResult['response'] !== true) { /* ... */ die("Error dari API Provider."); }

if (!isset($apiResult['data']) || !is_array($apiResult['data'])) {
    echo "API Sukses, tetapi key 'data' tidak valid.\n"; $apiServices = [];
} else {
    $apiServices = $apiResult['data'];
    echo "API Sukses! Jumlah item data diterima: " . count($apiServices) . "\n";
}

$uniqueApiCategories = [];
if (is_array($apiServices)) {
    foreach ($apiServices as $service) {
        if (isset($service['category_name']) && !isset($uniqueApiCategories[$service['category_name']])) {
            $uniqueApiCategories[$service['category_name']] = $service['category_name'];
        }
    }
}
echo "Jumlah kategori unik ditemukan di API: " . count($uniqueApiCategories) . "\n";

$categoriesAdded = 0;
$categoriesSkipped = 0;

if (!empty($uniqueApiCategories)) {
    echo "Memulai proses pengecekan dan penambahan kategori ke database lokal...\n";
    $pdo->beginTransaction(); 

    try {
        $stmtCheckCat = $pdo->prepare("SELECT id FROM categories WHERE name = :name LIMIT 1");
        $stmtInsertCat = $pdo->prepare("INSERT INTO categories (name, status, icon_class) VALUES (:name, 'active', :icon)");

        ksort($uniqueApiCategories);

        foreach ($uniqueApiCategories as $categoryName) {
            $categoryName = trim($categoryName); 
            if (empty($categoryName)) {
                echo "WARNING: Melewati nama kategori kosong dari API.\n";
                continue;
            }

            $stmtCheckCat->bindParam(':name', $categoryName);
            $stmtCheckCat->execute();
            $existingCategory = $stmtCheckCat->fetch(PDO::FETCH_ASSOC);

            if ($existingCategory) {
                echo "SKIP: Kategori '{$categoryName}' sudah ada.\n";
                $categoriesSkipped++;
            } else {
                $iconClass = 'fas fa-star'; // Default
                if (stripos($categoryName, 'instagram') !== false) $iconClass = 'fab fa-instagram';
                elseif (stripos($categoryName, 'facebook') !== false) $iconClass = 'fab fa-facebook';
                elseif (stripos($categoryName, 'tiktok') !== false) $iconClass = 'fab fa-tiktok';
                elseif (stripos($categoryName, 'youtube') !== false) $iconClass = 'fab fa-youtube';
                elseif (stripos($categoryName, 'telegram') !== false) $iconClass = 'fab fa-telegram-plane';
                elseif (stripos($categoryName, 'shopee') !== false) $iconClass = 'fas fa-shopping-bag';
                elseif (stripos($categoryName, 'spotify') !== false) $iconClass = 'fab fa-spotify';
                elseif (stripos($categoryName, 'twitter') !== false) $iconClass = 'fab fa-twitter';

                $stmtInsertCat->bindParam(':name', $categoryName);
                $stmtInsertCat->bindParam(':icon', $iconClass);

                if ($stmtInsertCat->execute()) {
                    $categoriesAdded++;
                    echo "INSERTED: Kategori '{$categoryName}' berhasil ditambahkan.\n";
                } else {
                    echo "ERROR: Gagal insert kategori '{$categoryName}'.\n";
                }
            }
        }

        $pdo->commit();
        echo "\n=====================================\n";
        echo "Proses Penyimpanan Kategori Selesai!\n";
        echo "=====================================\n";
        echo "Kategori Baru Ditambahkan: {$categoriesAdded}\n";
        echo "Kategori Dilewati (Sudah Ada): {$categoriesSkipped}\n";

    } catch (\Exception $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        echo "\n=====================================\n";
        echo "ERROR SELAMA PENYIMPANAN KATEGORI!\n";
        echo "=====================================\n";
        echo "Pesan Error: " . $e->getMessage() . "\n";
        echo "Transaksi dibatalkan (rollback).\n";
        die("Proses dihentikan karena error database.");
    }
} else {
    echo "Tidak ada kategori unik untuk diproses.\n";
}

echo "</pre>";
?>
