<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

/**
 * Admin AJAX handler for TLogs Marketplace Logs API settings.
 * API base: https://tlogsmarketplace.com/api.php
 *
 * Actions:
 *   save_xtralogtools_settings    — save API key, base URL, enabled flag, markup
 *   check_xtralogtools_balance    — test API key connectivity
 *   sync_xtralogtools_products    — fetch categories/products and upsert into xtralog_products
 *   update_xtralog_product_price  — update our_price for a single product
 *   toggle_xtralog_product        — enable/disable a product
 *   delete_all_xtralog_products   — remove all synced products
 *   debug_xtralogtools_raw        — dump raw API response for troubleshooting
 */

if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: application/json');

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

// ── Auth: admin only ──────────────────────────────────────────────────────────
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized']); exit();
}
try {
    $adm = $pdo->prepare("SELECT is_admin FROM users WHERE id = :id LIMIT 1");
    $adm->execute(['id' => $_SESSION['user_id']]);
    $adm_row = $adm->fetch(PDO::FETCH_ASSOC);
    if (!$adm_row || (int)$adm_row['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 request method']); exit();
}

define('XTL_DEFAULT_BASE', 'https://xtralogstools.com/api/v1');

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

// ── Helper: sanitize base URL ─────────────────────────────────────────────────
function xtl_sanitize_url(string $url): string {
    $url = trim($url);
    if (empty($url) || !filter_var($url, FILTER_VALIDATE_URL)) {
        return XTL_DEFAULT_BASE;
    }
    return rtrim($url, '/');
}

// ── Helper: load API class ────────────────────────────────────────────────
function xtl_load_class(): bool {
    $path = dirname(__DIR__, 2) . '/include/XtraLogTools.php';
    if (!file_exists($path)) return false;
    require_once $path;
    return true;
}

// ════════════════════════════════════════════════════════════════════════════
//  SAVE SETTINGS
// ════════════════════════════════════════════════════════════════════════════
if ($action === 'save_xtralogtools_settings') {
    $api_key = trim($_POST['xtralogtools_api_key']  ?? '');
    $api_url = xtl_sanitize_url($_POST['xtralogtools_api_url'] ?? '');
    $enabled = (int)($_POST['xtralogtools_enabled'] ?? 0);
    $markup  = max(0, (float)($_POST['xtralogtools_markup'] ?? 10.00));

    if (empty($api_key)) {
        echo json_encode(['status' => '0', 'msg' => 'API key is required.']); exit();
    }

    try {
        $pdo->exec("ALTER TABLE settings
            ADD COLUMN IF NOT EXISTS xtralogtools_api_key  VARCHAR(255) NOT NULL DEFAULT '',
            ADD COLUMN IF NOT EXISTS xtralogtools_api_url  VARCHAR(255) NOT NULL DEFAULT '" . XTL_DEFAULT_BASE . "',
            ADD COLUMN IF NOT EXISTS xtralogtools_enabled  TINYINT(1)   NOT NULL DEFAULT 0,
            ADD COLUMN IF NOT EXISTS xtralogtools_markup   DECIMAL(6,2) NOT NULL DEFAULT 10.00");

        $pdo->prepare("
            UPDATE settings SET
                xtralogtools_api_key = :key,
                xtralogtools_api_url = :url,
                xtralogtools_enabled = :enabled,
                xtralogtools_markup  = :markup
            WHERE id = 1
        ")->execute([
            'key'     => $api_key,
            'url'     => $api_url,
            'enabled' => $enabled,
            'markup'  => $markup,
        ]);

        echo json_encode(['status' => '1', 'msg' => 'Settings saved. API URL: ' . $api_url]);
    } catch (PDOException $e) {
        error_log('[logs_api_handler] save error: ' . $e->getMessage());
        echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    }
    exit();
}

// ════════════════════════════════════════════════════════════════════════════
//  CHECK BALANCE / CONNECTIVITY
// ════════════════════════════════════════════════════════════════════════════
if ($action === 'check_xtralogtools_balance') {
    $api_key = trim($_POST['api_key'] ?? '');
    $api_url = xtl_sanitize_url($_POST['api_url'] ?? '');

    if (empty($api_key)) {
        echo json_encode(['status' => '0', 'msg' => 'API key is required.']); exit();
    }
    if (!xtl_load_class()) {
        echo json_encode(['status' => '0', 'msg' => 'XtraLogTools.php not found in include/ folder.']); exit();
    }

    $xtl    = new XtraLogTools($api_key, $api_url);
    $result = $xtl->getBalance();

    if ($result['success']) {
        $bal = $result['balance'] ?? 'API connected ✓';
        echo json_encode(['status' => '1', 'balance' => htmlspecialchars((string)$bal)]);
    } else {
        echo json_encode(['status' => '0', 'msg' => $result['error'] ?? 'Could not connect to API.']);
    }
    exit();
}

// ════════════════════════════════════════════════════════════════════════════
//  SYNC PRODUCTS
//  Calls GET ?action=categories&api_key=KEY
// ════════════════════════════════════════════════════════════════════════════
if ($action === 'sync_xtralogtools_products') {
    $api_key = trim($_POST['api_key'] ?? '');
    $api_url = xtl_sanitize_url($_POST['api_url'] ?? '');
    $markup  = max(0, (float)($_POST['markup'] ?? 10.00));

    if (empty($api_key)) {
        echo json_encode(['status' => '0', 'msg' => 'API key is required.']); exit();
    }
    if (!xtl_load_class()) {
        echo json_encode(['status' => '0', 'msg' => 'XtraLogTools.php not found.']); exit();
    }

    ini_set('max_execution_time', 180);

    $xtl    = new XtraLogTools($api_key, $api_url);
    $result = $xtl->getServices();

    if (!$result['success']) {
        echo json_encode([
            'status' => '0',
            'msg'    => 'API error: ' . ($result['error'] ?? 'Unknown error') .
                        ' (URL used: ' . $api_url . '/services.php)',
        ]); exit();
    }

    $raw = $result['data'];

    // Collect products from ALL available service keys
    $products = [];
    $service_keys_found = [];

    // Check for logs_services first (preferred)
    if (!empty($raw['logs_services']) && is_array($raw['logs_services'])) {
        foreach ($raw['logs_services'] as $svc) { $svc['_source'] = 'logs_services'; $products[] = $svc; }
        $service_keys_found[] = 'logs_services';
    }
    // Also pull from otp_services
    if (!empty($raw['otp_services']) && is_array($raw['otp_services'])) {
        foreach ($raw['otp_services'] as $svc) { $svc['_source'] = 'otp_services'; $products[] = $svc; }
        $service_keys_found[] = 'otp_services';
    }
    // Also pull from rental_services
    if (!empty($raw['rental_services']) && is_array($raw['rental_services'])) {
        foreach ($raw['rental_services'] as $svc) { $svc['_source'] = 'rental_services'; $products[] = $svc; }
        $service_keys_found[] = 'rental_services';
    }
    // Also pull from smm_services
    if (!empty($raw['smm_services']) && is_array($raw['smm_services'])) {
        foreach ($raw['smm_services'] as $svc) { $svc['_source'] = 'smm_services'; $products[] = $svc; }
        $service_keys_found[] = 'smm_services';
    }

    if (empty($products)) {
        $available_keys = is_array($raw) ? implode(', ', array_keys($raw)) : 'none';
        echo json_encode([
            'status' => '0',
            'msg'    => 'No products found in API response. Keys returned: ' . $available_keys,
        ]); exit();
    }

    // Ensure table exists
    try {
        $pdo->exec("CREATE TABLE IF NOT EXISTS xtralog_products (
            id           INT AUTO_INCREMENT PRIMARY KEY,
            product_id   VARCHAR(100) NOT NULL UNIQUE,
            product_name VARCHAR(255) NOT NULL,
            description  TEXT,
            server       TINYINT(1)   NOT NULL DEFAULT 1,
            api_price    DECIMAL(10,2) NOT NULL DEFAULT 0.00,
            our_price    DECIMAL(10,2) NOT NULL DEFAULT 0.00,
            category     VARCHAR(100) NOT NULL DEFAULT '',
            status       TINYINT(1)   NOT NULL DEFAULT 1,
            synced_at    TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            KEY idx_status   (status),
            KEY idx_category (category)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
    } catch (PDOException $e) { /* already exists */ }

    $upserted = 0;
    $errors   = 0;

    foreach ($products as $svc) {
        if (!is_array($svc)) continue;

        $product_id   = trim((string)($svc['id']          ?? $svc['product_id']   ?? ''));
        $product_name = trim((string)($svc['name']        ?? $svc['product_name'] ?? $svc['title'] ?? ''));
        $description  = trim((string)($svc['description'] ?? $svc['desc']         ?? ''));
        $server       = (int)($svc['server']              ?? $svc['server_no']    ?? 1);
        $api_price    = (float)($svc['price']             ?? $svc['cost']         ?? $svc['amount'] ?? $svc['rate_per_1000'] ?? 0);
        $category     = trim((string)($svc['_source']     ?? $svc['category']     ?? $svc['type'] ?? ''));

        if (empty($product_id) || empty($product_name)) continue;

        $our_price = round($api_price * (1 + $markup / 100), 2);

        try {
            $pdo->prepare("
                INSERT INTO xtralog_products
                    (product_id, product_name, description, server, api_price, our_price, category, status, synced_at)
                VALUES
                    (:pid, :pname, :desc, :server, :api_price, :our_price, :cat, 1, NOW())
                ON DUPLICATE KEY UPDATE
                    product_name = VALUES(product_name),
                    description  = VALUES(description),
                    server       = VALUES(server),
                    api_price    = VALUES(api_price),
                    our_price    = IF(our_price = 0, VALUES(our_price), our_price),
                    category     = VALUES(category),
                    synced_at    = NOW()
            ")->execute([
                'pid'       => $product_id,
                'pname'     => $product_name,
                'desc'      => $description,
                'server'    => $server,
                'api_price' => $api_price,
                'our_price' => $our_price,
                'cat'       => $category,
            ]);
            $upserted++;
        } catch (PDOException $e) {
            error_log('[logs_api_handler] upsert error: ' . $e->getMessage());
            $errors++;
        }
    }

    $msg = "Sync complete. {$upserted} product(s) synced from: " . implode(', ', $service_keys_found) . ".";
    if ($errors > 0) $msg .= " {$errors} error(s) encountered.";

    echo json_encode(['status' => '1', 'msg' => $msg, 'count' => $upserted]);
    exit();
}

// ════════════════════════════════════════════════════════════════════════════
//  UPDATE PRODUCT PRICE
// ════════════════════════════════════════════════════════════════════════════
if ($action === 'update_xtralog_product_price') {
    $product_db_id = filter_var($_POST['product_db_id'] ?? 0, FILTER_VALIDATE_INT);
    $our_price     = max(0, (float)($_POST['our_price'] ?? 0));

    if (!$product_db_id) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid product ID.']); exit();
    }

    try {
        $pdo->prepare("UPDATE xtralog_products SET our_price = :price WHERE id = :id")
            ->execute(['price' => $our_price, 'id' => $product_db_id]);
        echo json_encode(['status' => '1', 'msg' => 'Price updated.']);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'DB error: ' . $e->getMessage()]);
    }
    exit();
}

// ════════════════════════════════════════════════════════════════════════════
//  TOGGLE PRODUCT STATUS
// ════════════════════════════════════════════════════════════════════════════
if ($action === 'toggle_xtralog_product') {
    $product_db_id = filter_var($_POST['product_db_id'] ?? 0, FILTER_VALIDATE_INT);
    $status        = (int)($_POST['status'] ?? 0) ? 1 : 0;

    if (!$product_db_id) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid product ID.']); exit();
    }

    try {
        $pdo->prepare("UPDATE xtralog_products SET status = :status WHERE id = :id")
            ->execute(['status' => $status, 'id' => $product_db_id]);
        echo json_encode(['status' => '1', 'msg' => 'Product ' . ($status ? 'enabled' : 'disabled') . '.']);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'DB error: ' . $e->getMessage()]);
    }
    exit();
}

// ════════════════════════════════════════════════════════════════════════════
//  DEBUG: DUMP RAW API RESPONSE
// ════════════════════════════════════════════════════════════════════════════
if ($action === 'debug_xtralogtools_raw') {
    $api_key = trim($_POST['api_key'] ?? '');
    $api_url = xtl_sanitize_url($_POST['api_url'] ?? '');

    if (empty($api_key)) {
        echo json_encode(['status' => '0', 'msg' => 'API key is required.']); exit();
    }
    if (!xtl_load_class()) {
        echo json_encode(['status' => '0', 'msg' => 'XtraLogTools.php not found.']); exit();
    }

    $xtl    = new XtraLogTools($api_key, $api_url);
    $result = $xtl->getServices();

    echo json_encode([
        'status'    => '1',
        'success'   => $result['success'],
        'http_code' => $result['code'],
        'error'     => $result['error'] ?? null,
        'top_keys'  => is_array($result['data']) ? array_keys($result['data']) : 'not an array',
        'raw'       => $result['data'],
        'url_used'  => $api_url . '?action=categories',
    ], JSON_PRETTY_PRINT);
    exit();
}

// ════════════════════════════════════════════════════════════════════════════
//  DELETE ALL PRODUCTS
// ════════════════════════════════════════════════════════════════════════════
if ($action === 'delete_all_xtralog_products') {
    try {
        $count = $pdo->query("SELECT COUNT(*) FROM xtralog_products")->fetchColumn();
        $pdo->exec("DELETE FROM xtralog_products");
        echo json_encode(['status' => '1', 'msg' => "Deleted {$count} product(s) from the database."]);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'DB error: ' . $e->getMessage()]);
    }
    exit();
}

// ── Unknown action ────────────────────────────────────────────────────────────
echo json_encode(['status' => '0', 'msg' => 'Unknown action: ' . htmlspecialchars($action)]);
