<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
// ─────────────────────────────────────────────────────────────────────────────
// ajax/reloadly_ajax.php
// Handles all AJAX actions for the Reloadly Gift Card admin pages.
// Include/require this file from ajax/update_settings.php or route directly.
// ─────────────────────────────────────────────────────────────────────────────

if (session_status() === PHP_SESSION_NONE) session_start();

$config_path = dirname(__DIR__, 2) . '/include/config.php';
if (file_exists($config_path)) {
    include($config_path);
} else {
    echo json_encode(['status' => '0', 'msg' => 'Configuration file not found']);
    exit();
}

header('Content-Type: application/json; charset=utf-8');

// ── Auth guard ────────────────────────────────────────────────────────────────
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized']);
    exit();
}
try {
    $stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :uid");
    $stmt->execute([':uid' => $_SESSION['user_id']]);
    $adm = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$adm || $adm['is_admin'] != 1) { echo json_encode(['status' => '0', 'msg' => 'Unauthorized']); exit(); }
} catch (PDOException $e) {
    echo json_encode(['status' => '0', 'msg' => 'Auth error']); exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid method']); exit();
}

$action = trim($_POST['action'] ?? '');

// ════════════════════════════════════════════════════════════════
// ACTION: Save Reloadly API Settings
// ════════════════════════════════════════════════════════════════
if ($action === 'save_reloadly_settings') {
    $fields = [
        'reloadly_client_id'     => trim($_POST['reloadly_client_id']     ?? ''),
        'reloadly_client_secret' => trim($_POST['reloadly_client_secret'] ?? ''),
        'reloadly_sandbox'       => isset($_POST['reloadly_sandbox'])  ? (int)$_POST['reloadly_sandbox']  : 1,
        'reloadly_enabled'       => isset($_POST['reloadly_enabled'])  ? (int)$_POST['reloadly_enabled']  : 0,
        'reloadly_markup'        => (float)($_POST['reloadly_markup']   ?? 10),
        'reloadly_ngn_rate'      => (float)($_POST['reloadly_ngn_rate'] ?? 1600),
    ];

    try {
        $pdo->prepare("UPDATE settings SET
            reloadly_client_id     = :reloadly_client_id,
            reloadly_client_secret = :reloadly_client_secret,
            reloadly_sandbox       = :reloadly_sandbox,
            reloadly_enabled       = :reloadly_enabled,
            reloadly_markup        = :reloadly_markup,
            reloadly_ngn_rate      = :reloadly_ngn_rate
            WHERE id = 1")->execute($fields);
        echo json_encode(['status' => '1', 'msg' => 'Reloadly settings saved successfully.']);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'DB error: ' . $e->getMessage()]);
    }
    exit();
}

// ════════════════════════════════════════════════════════════════
// ACTION: Sync Gift Cards from Reloadly API
// ════════════════════════════════════════════════════════════════
if ($action === 'sync_giftcards') {
    require_once dirname(__DIR__, 2) . '/include/Reloadly.php';

    $cfg = $pdo->query("SELECT * FROM settings WHERE id = 1 LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if (empty($cfg['reloadly_client_id'])) {
        echo json_encode(['status' => '0', 'msg' => 'Reloadly credentials not configured.']);
        exit();
    }

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

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

    // Fetch all products paginated
    $all_products = [];
    $page = 1;
    do {
        $result = $reloadly->getProducts($page, 200);
        if (!$result['success']) {
            echo json_encode(['status' => '0', 'msg' => 'Reloadly API error: ' . $result['error']]);
            exit();
        }
        $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);

    // Fetch discount map
    $discount_map = [];
    $dresult = $reloadly->getDiscounts(1, 500);
    if ($dresult['success']) {
        foreach ($dresult['data']['content'] ?? [] as $d) {
            $pid = $d['product']['productId'] ?? null;
            if ($pid) $discount_map[$pid] = (float)($d['discountPercentage'] ?? 0);
        }
    }

    // Upsert 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()
    ");

    $synced = $failed = $skipped = 0;
    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 ? (float)($p['minSenderDenomination'] ?? $p['minRecipientDenomination'] ?? 0) : null;
        $max_amount   = $is_range ? (float)($p['maxSenderDenomination'] ?? $p['maxRecipientDenomination'] ?? 0) : null;
        $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) {
            $failed++;
        }
    }

    $pdo->prepare("UPDATE settings SET reloadly_last_sync = NOW() WHERE id = 1")->execute();

    echo json_encode([
        'status' => '1',
        'msg'    => "✅ Sync complete! <br><strong>Synced:</strong> {$synced} &nbsp; <strong>Failed:</strong> {$failed} &nbsp; <strong>Skipped:</strong> {$skipped}",
    ]);
    exit();
}

// ════════════════════════════════════════════════════════════════
// ACTION: Recalculate All Gift Card Prices
// ════════════════════════════════════════════════════════════════
if ($action === 'recalc_giftcard_prices') {
    $markup   = (float)($_POST['markup']   ?? 10);
    $ngn_rate = (float)($_POST['ngn_rate'] ?? 1600);

    try {
        $count = (int)$pdo->query("SELECT COUNT(*) FROM gift_card_products")->fetchColumn();
        $pdo->prepare("UPDATE gift_card_products SET ngn_sell_rate = :r, markup_percent = :m")
            ->execute(['r' => $ngn_rate, 'm' => $markup]);
        $pdo->prepare("UPDATE settings SET reloadly_markup = :m, reloadly_ngn_rate = :r WHERE id = 1")
            ->execute(['m' => $markup, 'r' => $ngn_rate]);
        echo json_encode(['status' => '1', 'msg' => "{$count} products updated. Markup: {$markup}% | Rate: ₦" . number_format($ngn_rate, 2) . " per USD."]);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'DB error: ' . $e->getMessage()]);
    }
    exit();
}

// ════════════════════════════════════════════════════════════════
// ACTION: Edit / Update a single Gift Card Product
// ════════════════════════════════════════════════════════════════
if ($action === 'edit_product') {
    $id             = (int)($_POST['id']             ?? 0);
    $product_name   = trim($_POST['product_name']    ?? '');
    $brand_name     = trim($_POST['brand_name']      ?? '');
    $markup_percent = (float)($_POST['markup_percent'] ?? 10);
    $ngn_sell_rate  = (float)($_POST['ngn_sell_rate']  ?? 1600);
    $status         = (int)($_POST['status']           ?? 1);
    $image_url      = trim($_POST['image_url']         ?? '');
    $denominations  = trim($_POST['denominations']     ?? '');
    $min_amount     = !empty($_POST['min_amount']) ? (float)$_POST['min_amount'] : null;
    $max_amount     = !empty($_POST['max_amount']) ? (float)$_POST['max_amount'] : null;

    if (!$id || empty($product_name)) {
        echo json_encode(['status' => '0', 'msg' => 'Product name is required.']); exit();
    }

    // Normalise denominations — accept "5, 10, 25" or "[5,10,25]"
    if ($denominations !== '') {
        $denominations = preg_replace('/\s+/', '', $denominations);
        if ($denominations[0] !== '[') {
            $arr = array_map('floatval', explode(',', trim($denominations, '[]')));
            $denominations = json_encode($arr);
        } else {
            $arr = json_decode($denominations, true);
            $denominations = $arr !== null ? json_encode($arr) : $denominations;
        }
    } else {
        $denominations = null;
    }

    try {
        $pdo->prepare("UPDATE gift_card_products SET
            product_name   = :pname,
            brand_name     = :bname,
            markup_percent = :markup,
            ngn_sell_rate  = :rate,
            status         = :status,
            image_url      = :img,
            denominations  = :denoms,
            min_amount     = :minA,
            max_amount     = :maxA,
            updated_at     = NOW()
            WHERE id = :id")->execute([
            'pname'  => $product_name,
            'bname'  => $brand_name,
            'markup' => $markup_percent,
            'rate'   => $ngn_sell_rate,
            'status' => $status,
            'img'    => $image_url ?: null,
            'denoms' => $denominations,
            'minA'   => $min_amount,
            'maxA'   => $max_amount,
            'id'     => $id,
        ]);
        echo json_encode(['status' => '1', 'msg' => 'Product updated successfully.']);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'DB error: ' . $e->getMessage()]);
    }
    exit();
}

// ════════════════════════════════════════════════════════════════
// ACTION: Delete a Gift Card Product
// ════════════════════════════════════════════════════════════════
if ($action === 'delete_product') {
    $id = (int)($_POST['id'] ?? 0);
    if (!$id) { echo json_encode(['status' => '0', 'msg' => 'Invalid product ID.']); exit(); }
    try {
        $pdo->prepare("DELETE FROM gift_card_products WHERE id = :id")->execute([':id' => $id]);
        echo json_encode(['status' => '1', 'msg' => 'Product deleted.']);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'DB error: ' . $e->getMessage()]);
    }
    exit();
}

// ════════════════════════════════════════════════════════════════
// ACTION: Toggle product status (enable/disable)
// ════════════════════════════════════════════════════════════════
if ($action === 'toggle_product_status') {
    $id = (int)($_POST['id'] ?? 0);
    if (!$id) { echo json_encode(['status' => '0', 'msg' => 'Invalid ID.']); exit(); }
    try {
        $pdo->prepare("UPDATE gift_card_products SET status = IF(status=1,0,1), updated_at = NOW() WHERE id = :id")->execute([':id' => $id]);
        $new = (int)$pdo->query("SELECT status FROM gift_card_products WHERE id = {$id}")->fetchColumn();
        echo json_encode(['status' => '1', 'new_status' => $new, 'msg' => $new ? 'Product activated.' : 'Product hidden.']);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => $e->getMessage()]);
    }
    exit();
}

// ════════════════════════════════════════════════════════════════
// ACTION: Update Gift Card Order Status
// ════════════════════════════════════════════════════════════════
if ($action === 'update_order_status') {
    $id     = (int)($_POST['id']     ?? 0);
    $status = trim($_POST['status']  ?? '');
    $allowed = ['pending', 'completed', 'failed', 'refunded'];
    if (!$id || !in_array($status, $allowed)) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid parameters.']); exit();
    }
    try {
        $pdo->prepare("UPDATE gift_card_orders SET status = :s, updated_at = NOW() WHERE id = :id")
            ->execute([':s' => $status, ':id' => $id]);
        echo json_encode(['status' => '1', 'msg' => 'Order status updated to ' . $status . '.']);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => $e->getMessage()]);
    }
    exit();
}

// ════════════════════════════════════════════════════════════════
// ACTION: Fetch Redeem Code from Reloadly for an order
// ════════════════════════════════════════════════════════════════
if ($action === 'fetch_card_code') {
    $order_id = (int)($_POST['order_id'] ?? 0);
    $txn_id   = (int)($_POST['txn_id']   ?? 0);
    if (!$order_id || !$txn_id) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid order or transaction ID.']); exit();
    }

    require_once dirname(__DIR__, 2) . '/include/Reloadly.php';
    $cfg = $pdo->query("SELECT * FROM settings WHERE id = 1 LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    $reloadly = new Reloadly(
        $cfg['reloadly_client_id'],
        $cfg['reloadly_client_secret'],
        (bool)($cfg['reloadly_sandbox'] ?? 1)
    );

    $result = $reloadly->getRedeemCode($txn_id);
    if (!$result['success']) {
        echo json_encode(['status' => '0', 'msg' => 'Reloadly error: ' . $result['error']]); exit();
    }

    $cards      = $result['data'];
    $first      = is_array($cards) ? ($cards[0] ?? $cards) : $cards;
    $card_num   = $first['cardNumber'] ?? $first['code']    ?? null;
    $card_pin   = $first['pinCode']    ?? $first['pin']     ?? null;
    $redeem_url = $first['redemptionUrl'] ?? null;

    if (!$card_num) {
        echo json_encode(['status' => '0', 'msg' => 'Card code not available from Reloadly.']); exit();
    }

    try {
        $pdo->prepare("UPDATE gift_card_orders SET card_number = :cn, card_pin = :cp, redeem_url = :ru, updated_at = NOW() WHERE id = :id")
            ->execute([':cn' => $card_num, ':cp' => $card_pin, ':ru' => $redeem_url, ':id' => $order_id]);
    } catch (PDOException $e) { /* log but still return card */ }

    echo json_encode([
        'status'      => '1',
        'card_number' => $card_num,
        'card_pin'    => $card_pin,
        'redeem_url'  => $redeem_url,
        'msg'         => 'Card code retrieved successfully.',
    ]);
    exit();
}

// ════════════════════════════════════════════════════════════════
// ACTION: Add Order Note
// ════════════════════════════════════════════════════════════════
if ($action === 'add_order_note') {
    $id   = (int)($_POST['id']   ?? 0);
    $note = trim($_POST['note']  ?? '');
    if (!$id) { echo json_encode(['status' => '0', 'msg' => 'Invalid ID.']); exit(); }
    try {
        $pdo->prepare("UPDATE gift_card_orders SET notes = :n, updated_at = NOW() WHERE id = :id")
            ->execute([':n' => $note, ':id' => $id]);
        echo json_encode(['status' => '1', 'msg' => 'Note saved.']);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => $e->getMessage()]);
    }
    exit();
}

// Fall-through (not handled here — let the main update_settings.php continue)