<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
// ajax/sell-giftcard-admin-ajax.php
// Handles all admin AJAX actions for the Sell Gift Card feature.

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');

// ── Admin 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: Add a new sell gift card type
// ════════════════════════════════════════════════════════════════
if ($action === 'add_sell_type') {
    $name      = htmlspecialchars(trim($_POST['name']      ?? ''), ENT_QUOTES);
    $image_url = trim($_POST['image_url'] ?? '');
    $currency  = strtoupper(trim($_POST['currency'] ?? 'USD'));
    $ngn_rate  = (float)($_POST['ngn_rate'] ?? 0);
    $min_usd   = (float)($_POST['min_usd']  ?? 1);
    $max_usd   = (float)($_POST['max_usd']  ?? 1000);
    $status    = (int)($_POST['status']     ?? 1);

    if (empty($name))   { echo json_encode(['status' => '0', 'msg' => 'Card name is required.']); exit; }
    if ($ngn_rate <= 0) { echo json_encode(['status' => '0', 'msg' => 'NGN rate must be greater than 0.']); exit; }
    if ($min_usd <= 0 || $max_usd <= 0 || $min_usd >= $max_usd) {
        echo json_encode(['status' => '0', 'msg' => 'Min must be less than Max and both positive.']); exit;
    }

    try {
        $pdo->prepare("INSERT INTO sell_giftcard_types (name, image_url, currency, ngn_rate, min_usd, max_usd, status)
                       VALUES (:name, :img, :cur, :rate, :min, :max, :st)")
            ->execute([
                'name' => $name,
                'img'  => $image_url ?: null,
                'cur'  => $currency,
                'rate' => $ngn_rate,
                'min'  => $min_usd,
                'max'  => $max_usd,
                'st'   => $status,
            ]);
        echo json_encode(['status' => '1', 'msg' => "Gift card type '{$name}' added successfully."]);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'DB error: ' . $e->getMessage()]);
    }
    exit;
}

// ════════════════════════════════════════════════════════════════
//  ACTION: Edit / Update a sell gift card type
// ════════════════════════════════════════════════════════════════
if ($action === 'edit_sell_type') {
    $id        = (int)($_POST['id'] ?? 0);
    $name      = htmlspecialchars(trim($_POST['name']      ?? ''), ENT_QUOTES);
    $image_url = trim($_POST['image_url'] ?? '');
    $currency  = strtoupper(trim($_POST['currency'] ?? 'USD'));
    $ngn_rate  = (float)($_POST['ngn_rate'] ?? 0);
    $min_usd   = (float)($_POST['min_usd']  ?? 1);
    $max_usd   = (float)($_POST['max_usd']  ?? 1000);
    $status    = (int)($_POST['status']     ?? 1);

    if (!$id || empty($name)) {
        echo json_encode(['status' => '0', 'msg' => 'Card name is required.']); exit;
    }
    if ($ngn_rate <= 0) {
        echo json_encode(['status' => '0', 'msg' => 'NGN rate must be greater than 0.']); exit;
    }
    if ($min_usd <= 0 || $max_usd <= 0 || $min_usd >= $max_usd) {
        echo json_encode(['status' => '0', 'msg' => 'Min must be less than Max and both positive.']); exit;
    }

    try {
        $pdo->prepare("UPDATE sell_giftcard_types SET
            name = :name, image_url = :img, currency = :cur,
            ngn_rate = :rate, min_usd = :min, max_usd = :max,
            status = :st, updated_at = NOW()
            WHERE id = :id")
            ->execute([
                'name' => $name,
                'img'  => $image_url ?: null,
                'cur'  => $currency,
                'rate' => $ngn_rate,
                'min'  => $min_usd,
                'max'  => $max_usd,
                'st'   => $status,
                'id'   => $id,
            ]);
        echo json_encode(['status' => '1', 'msg' => "Card type updated successfully."]);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'DB error: ' . $e->getMessage()]);
    }
    exit;
}

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

// ════════════════════════════════════════════════════════════════
//  ACTION: Delete a sell gift card type
// ════════════════════════════════════════════════════════════════
if ($action === 'delete_sell_type') {
    $id = (int)($_POST['id'] ?? 0);
    if (!$id) { echo json_encode(['status' => '0', 'msg' => 'Invalid ID.']); exit; }

    // Safety: check no pending orders reference this type
    $in_use = (int)$pdo->query("SELECT COUNT(*) FROM sell_giftcard_orders WHERE type_id = {$id} AND status = 'pending'")->fetchColumn();
    if ($in_use > 0) {
        echo json_encode(['status' => '0', 'msg' => "Cannot delete: {$in_use} pending order(s) use this card type. Resolve them first."]); exit;
    }

    try {
        $pdo->prepare("DELETE FROM sell_giftcard_types WHERE id = :id")->execute([':id' => $id]);
        echo json_encode(['status' => '1', 'msg' => 'Card type deleted successfully.']);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'DB error: ' . $e->getMessage()]);
    }
    exit;
}

// ════════════════════════════════════════════════════════════════
//  ACTION: Approve a sell order (mark as paid)
// ════════════════════════════════════════════════════════════════
if ($action === 'approve_sell_order') {
    $id = (int)($_POST['id'] ?? 0);
    if (!$id) { echo json_encode(['status' => '0', 'msg' => 'Invalid order ID.']); exit; }

    try {
        // Check order exists and is still pending
        $ord = $pdo->query("SELECT * FROM sell_giftcard_orders WHERE id = {$id} LIMIT 1")->fetch(PDO::FETCH_ASSOC);
        if (!$ord) {
            echo json_encode(['status' => '0', 'msg' => 'Order not found.']); exit;
        }
        if ($ord['status'] !== 'pending') {
            echo json_encode(['status' => '0', 'msg' => "Order is already {$ord['status']}."]); exit;
        }

        $pdo->prepare("UPDATE sell_giftcard_orders SET status = 'approved', updated_at = NOW() WHERE id = :id")
            ->execute([':id' => $id]);

        // Optional: send Telegram notification to user (if bot is configured)
        if (!empty($site_data['telegram_notifications_enabled']) &&
            !empty($site_data['telegram_bot_token']) &&
            !empty($site_data['telegram_admin_chat_id'])) {
            $msg = "✅ Sell Order #{$id} APPROVED!\n"
                 . "Card: {$ord['type_name']}\n"
                 . "Payout: ₦" . number_format($ord['ngn_payout'], 2) . "\n"
                 . "Bank: {$ord['bank_name']} | {$ord['account_number']}\n"
                 . "Acc. Name: {$ord['account_name']}";
            @file_get_contents(
                "https://api.telegram.org/bot{$site_data['telegram_bot_token']}/sendMessage?"
                . http_build_query(['chat_id' => $site_data['telegram_admin_chat_id'], 'text' => $msg])
            );
        }

        echo json_encode(['status' => '1', 'msg' => "Order #{$id} approved and marked as paid."]);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'DB error: ' . $e->getMessage()]);
    }
    exit;
}

// ════════════════════════════════════════════════════════════════
//  ACTION: Reject a sell order with reason
// ════════════════════════════════════════════════════════════════
if ($action === 'reject_sell_order') {
    $id     = (int)($_POST['id']     ?? 0);
    $reason = trim($_POST['reason']  ?? '');

    if (!$id) { echo json_encode(['status' => '0', 'msg' => 'Invalid order ID.']); exit; }
    if (strlen($reason) < 3) {
        echo json_encode(['status' => '0', 'msg' => 'A rejection reason is required.']); exit;
    }

    try {
        $ord = $pdo->query("SELECT * FROM sell_giftcard_orders WHERE id = {$id} LIMIT 1")->fetch(PDO::FETCH_ASSOC);
        if (!$ord) { echo json_encode(['status' => '0', 'msg' => 'Order not found.']); exit; }
        if ($ord['status'] !== 'pending') {
            echo json_encode(['status' => '0', 'msg' => "Order is already {$ord['status']}."]); exit;
        }

        $pdo->prepare("UPDATE sell_giftcard_orders SET status = 'rejected', rejection_reason = :r, updated_at = NOW() WHERE id = :id")
            ->execute([':r' => $reason, ':id' => $id]);

        // Telegram notification
        if (!empty($site_data['telegram_notifications_enabled']) &&
            !empty($site_data['telegram_bot_token']) &&
            !empty($site_data['telegram_admin_chat_id'])) {
            $msg = "❌ Sell Order #{$id} REJECTED\n"
                 . "Card: {$ord['type_name']}\n"
                 . "Reason: {$reason}";
            @file_get_contents(
                "https://api.telegram.org/bot{$site_data['telegram_bot_token']}/sendMessage?"
                . http_build_query(['chat_id' => $site_data['telegram_admin_chat_id'], 'text' => $msg])
            );
        }

        echo json_encode(['status' => '1', 'msg' => "Order #{$id} rejected. Reason stored."]);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'DB error: ' . $e->getMessage()]);
    }
    exit;
}

// ════════════════════════════════════════════════════════════════
//  ACTION: Add admin note to an order
// ════════════════════════════════════════════════════════════════
if ($action === 'add_sell_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 sell_giftcard_orders SET admin_note = :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
echo json_encode(['status' => '0', 'msg' => 'Invalid action.']);
exit;