<?php
/**
 * Cron: Sync SMM Prices from JAP API
 * Developer: core tech web design
 * Whatsapp: +234 9162671360
 * Telegram: @jeditech
 *
 * Schedule: Every 10 minutes
 *
 * This script:
 *  1. Reads JAP API key, URL and markup from the settings table
 *  2. Fetches the latest service prices from the JAP API
 *  3. Updates jap_rate and our_rate for all matching services in smm_services
 *  4. Records the last sync timestamp in settings.last_price_sync
 *  5. Writes a log entry to cron/logs/sync_smm_prices.log
 */

// ── Bootstrap ────────────────────────────────────────────────
define('CRON_RUN', true);

// Resolve project root (one level up from /cron)
$root = dirname(__DIR__);

$config_path = $root . '/include/config.php';
if (!file_exists($config_path)) {
    die("[CRON ERROR] config.php not found at: {$config_path}\n");
}
include $config_path;  // provides $pdo

$jap_path = $root . '/include/JAP.php';
if (!file_exists($jap_path)) {
    die("[CRON ERROR] JAP.php not found at: {$jap_path}\n");
}
require_once $jap_path;

// ── Logging helper ───────────────────────────────────────────
$log_dir  = __DIR__ . '/logs';
$log_file = $log_dir . '/sync_smm_prices.log';

if (!is_dir($log_dir)) {
    mkdir($log_dir, 0755, true);
}

function cron_log(string $message, string $log_file): void {
    $line = '[' . date('Y-m-d H:i:s') . '] ' . $message . PHP_EOL;
    file_put_contents($log_file, $line, FILE_APPEND | LOCK_EX);
    echo $line; // also output to stdout (visible in manual runs)
}

// ── Load settings from DB ─────────────────────────────────────
try {
    $site = $pdo->query("SELECT jap_api_key, jap_api_url, smm_markup FROM settings WHERE id = 1")
                ->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    cron_log("DB ERROR (load settings): " . $e->getMessage(), $log_file);
    exit(1);
}

if (empty($site['jap_api_key'])) {
    cron_log("SKIP — JAP API key is not set in settings.", $log_file);
    exit(0);
}

$api_key = trim($site['jap_api_key']);
$api_url = trim($site['jap_api_url'] ?? 'https://the-owlet.com/api/v2');
$markup  = (float)($site['smm_markup'] ?? 30);

// ── Fetch services from JAP ───────────────────────────────────
$jap = new JAP($api_key, $api_url);
$res = $jap->getServices();

if (!$res['success']) {
    cron_log("JAP API ERROR: " . ($res['error'] ?? 'Unknown error'), $log_file);
    exit(1);
}

$services = $res['data'] ?? [];
if (empty($services) || !is_array($services)) {
    cron_log("WARNING — No services returned from JAP API.", $log_file);
    exit(0);
}

// ── Update prices in DB ───────────────────────────────────────
$updated  = 0;
$no_match = 0;

try {
    $stmt = $pdo->prepare(
        "UPDATE smm_services
            SET jap_rate   = :jap_rate,
                our_rate   = :our_rate,
                updated_at = NOW()
          WHERE jap_service_id = :jap_id"
    );

    foreach ($services as $s) {
        $jap_id   = (int)($s['service'] ?? 0);
        $jap_rate = (float)($s['rate']   ?? 0);

        if (!$jap_id) continue;

        $our_rate = round($jap_rate * (1 + $markup / 100), 2);

        $stmt->execute([
            'jap_rate' => $jap_rate,
            'our_rate' => $our_rate,
            'jap_id'   => $jap_id,
        ]);

        if ($stmt->rowCount() > 0) {
            $updated++;
        } else {
            $no_match++;
        }
    }

    // ── Update last_price_sync timestamp ─────────────────────
    $pdo->prepare("UPDATE settings SET last_price_sync = NOW() WHERE id = 1")->execute();

} catch (PDOException $e) {
    cron_log("DB ERROR (update prices): " . $e->getMessage(), $log_file);
    exit(1);
}

// ── Log result ────────────────────────────────────────────────
cron_log(
    "OK — {$updated} prices updated | {$no_match} JAP IDs not in local DB | Markup: {$markup}% | API: {$api_url}",
    $log_file
);

exit(0);