<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
/**
 * admin/sync-giftcards.php
 * Admin tool: syncs gift card product catalog from Reloadly API → gift_card_products table.
 * Place inside your /admin/ folder. Protect behind admin session check.
 *
 * Run: visit /admin/sync-giftcards.php (or trigger via admin panel button)
 * Can also be run via CLI: php admin/sync-giftcards.php
 */

// ── Admin auth guard ─────────────────────────────────────────────────────────
if (php_sapi_name() !== 'cli') {
    include('include/header.php');
    // Uncomment your admin session check:
    // if (empty($admin) || $admin['role'] !== 'admin') { header('Location: /'); exit; }
}

require_once dirname(__DIR__) . '/include/Reloadly.php';

// ── Load settings ─────────────────────────────────────────────────────────────
try {
    $cfg = $pdo->query("SELECT * FROM settings WHERE id = 1 LIMIT 1")->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    die('DB error: ' . $e->getMessage());
}

if (empty($cfg['reloadly_client_id'])) {
    die('Reloadly credentials not configured in settings.');
}

$reloadly = new Reloadly(
    $cfg['reloadly_client_id'],
    $cfg['reloadly_client_secret'],
    (bool)($cfg['reloadly_sandbox'] ?? 0)
);

$markup   = (float)($cfg['reloadly_markup']  ?? 10);
$ngn_rate = (float)($cfg['reloadly_ngn_rate'] ?? 1600);

$synced = $failed = $skipped = 0;
$log    = [];

// ── Fetch all products (paginated) ────────────────────────────────────────────
$all_products = [];
$page         = 1;
$page_size    = 200;

do {
    $result = $reloadly->getProducts($page, $page_size);
    if (!$result['success']) {
        $log[] = '❌ Failed to fetch page ' . $page . ': ' . $result['error'];
        break;
    }
    $content  = $result['data']['content'] ?? $result['data'] ?? [];
    $all_products = array_merge($all_products, $content);

    $total_pages = $result['data']['totalPages'] ?? 1;
    $page++;
} while ($page <= $total_pages && count($all_products) < 5000);

$log[] = '📦 Fetched ' . count($all_products) . ' products from Reloadly.';

// ── Fetch discounts map ───────────────────────────────────────────────────────
$discount_map = [];
$dresult = $reloadly->getDiscounts(1, 500);
if ($dresult['success']) {
    $dcontent = $dresult['data']['content'] ?? [];
    foreach ($dcontent as $d) {
        $pid = $d['product']['productId'] ?? null;
        if ($pid) $discount_map[$pid] = (float)($d['discountPercentage'] ?? 0);
    }
    $log[] = '🏷 Loaded ' . count($discount_map) . ' discounted products.';
}

// ── Upsert into gift_card_products ────────────────────────────────────────────
$upsert = $pdo->prepare("
    INSERT INTO gift_card_products
        (product_id, product_name, brand_id, brand_name, country_code, country_name,
         currency_code, ngn_sell_rate, markup_percent, denominations,
         min_amount, max_amount, discount_percent, image_url, status, is_range)
    VALUES
        (:pid, :pname, :bid, :bname, :cc, :cname,
         :cur, :rate, :markup, :denoms,
         :minA, :maxA, :disc, :img, 1, :isrange)
    ON DUPLICATE KEY UPDATE
        product_name    = VALUES(product_name),
        brand_id        = VALUES(brand_id),
        brand_name      = VALUES(brand_name),
        country_name    = VALUES(country_name),
        currency_code   = VALUES(currency_code),
        ngn_sell_rate   = VALUES(ngn_sell_rate),
        markup_percent  = VALUES(markup_percent),
        denominations   = VALUES(denominations),
        min_amount      = VALUES(min_amount),
        max_amount      = VALUES(max_amount),
        discount_percent= VALUES(discount_percent),
        image_url       = VALUES(image_url),
        is_range        = VALUES(is_range),
        updated_at      = NOW()
");

foreach ($all_products as $p) {
    $pid = (int)($p['productId'] ?? 0);
    if (!$pid) { $skipped++; continue; }

    $fixed_denoms = $p['fixedSenderDenominations'] ?? $p['fixedRecipientDenominations'] ?? [];
    $is_range     = empty($fixed_denoms) ? 1 : 0;
    $min_amount   = !$is_range ? null : (float)($p['minSenderDenomination'] ?? $p['minRecipientDenomination'] ?? 0);
    $max_amount   = !$is_range ? null : (float)($p['maxSenderDenomination'] ?? $p['maxRecipientDenomination'] ?? 0);
    $denoms_json  = !$is_range ? json_encode(array_values($fixed_denoms)) : null;
    $country_code = $p['country']['isoName'] ?? ($p['countryCode'] ?? 'US');
    $country_name = $p['country']['name']    ?? $country_code;
    $currency     = $p['senderCurrencyCode'] ?? ($p['recipientCurrencyCode'] ?? 'USD');
    $brand_id     = (int)($p['brand']['brandId'] ?? 0);
    $brand_name   = $p['brand']['brandName'] ?? ($p['productName'] ?? '');
    $image_url    = $p['logoUrls'][0] ?? null;
    $discount     = $discount_map[$pid] ?? 0.0;

    try {
        $upsert->execute([
            'pid'     => $pid,
            'pname'   => $p['productName'] ?? '',
            'bid'     => $brand_id ?: null,
            'bname'   => $brand_name,
            'cc'      => $country_code,
            'cname'   => $country_name,
            'cur'     => $currency,
            'rate'    => $ngn_rate,
            'markup'  => $markup,
            'denoms'  => $denoms_json,
            'minA'    => $min_amount,
            'maxA'    => $max_amount,
            'disc'    => $discount,
            'img'     => $image_url,
            'isrange' => $is_range,
        ]);
        $synced++;
    } catch (PDOException $e) {
        $log[] = '⚠ Skip product ' . $pid . ': ' . $e->getMessage();
        $failed++;
    }
}

// ── Update last sync time ─────────────────────────────────────────────────────
try {
    $pdo->prepare("UPDATE settings SET reloadly_last_sync = NOW() WHERE id = 1")->execute();
} catch (PDOException $e) {}

$log[] = "✅ Done. Synced: {$synced} | Failed: {$failed} | Skipped: {$skipped}";

// ── Output ────────────────────────────────────────────────────────────────────
if (php_sapi_name() === 'cli') {
    foreach ($log as $line) echo $line . PHP_EOL;
} else {
    echo '<!DOCTYPE html><html><head><title>Gift Card Sync</title>
    <style>body{font-family:monospace;padding:30px;background:#0f172a;color:#e2e8f0;line-height:1.8}
    h2{color:#a5b4fc}pre{background:#1e293b;padding:20px;border-radius:10px;}</style></head><body>';
    echo '<h2>🎁 Gift Card Catalog Sync</h2><pre>' . implode("\n", $log) . '</pre>';
    echo '<br><a href="../admin" style="color:#a5b4fc">← Back to Admin</a></body></html>';
}