<?php
/**
 * Cron: كل يوم الساعة 8 صباحاً
 * 0 8 * * * php /var/www/sudanna/cron/daily_kpi.php
 */
require_once dirname(__DIR__).'/config.php';

try {
    $date   = date('Y-m-d');
    $stats  = [];

    // مستخدمون جدد
    $s = db()->prepare("SELECT COUNT(*) FROM users WHERE DATE(created_at)=?");
    $s->execute([$date]);
    $stats['new_users'] = (int)$s->fetchColumn();

    // طلبات AI
    $s = db()->prepare("SELECT COUNT(*) FROM execution_log WHERE DATE(created_at)=?");
    $s->execute([$date]);
    $stats['ai_requests'] = (int)$s->fetchColumn();

    // حجوزات
    $s = db()->prepare("SELECT COUNT(*) FROM bookings WHERE DATE(created_at)=?");
    $s->execute([$date]);
    $stats['bookings'] = (int)$s->fetchColumn();

    // إيرادات
    $s = db()->prepare("SELECT COALESCE(SUM(amount_sdg),0) FROM wallet_transactions WHERE type='credit' AND DATE(created_at)=?");
    $s->execute([$date]);
    $stats['revenue_sdg'] = (float)$s->fetchColumn();

    // حفظ التقرير
    foreach ($stats as $key => $val) {
        db()->prepare(
            "INSERT INTO market_intelligence (category,city,metric_key,metric_val,recorded_at)
             VALUES ('platform','all',?,?,?) ON DUPLICATE KEY UPDATE metric_val=VALUES(metric_val)"
        )->execute([$key, $val, $date]);
    }

    echo "[daily_kpi] " . date('Y-m-d H:i:s') . " — " . json_encode($stats) . "\n";
} catch (Throwable $e) {
    error_log("[daily_kpi] " . $e->getMessage());
}
