<?php
// api/neg-cron.php — Cron nocturno: aplica negativos automáticos para todos los clientes en modo auto
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../credentials.php';

$is_cli     = php_sapi_name() === 'cli';
$cron_token = defined('CRON_SECRET') ? CRON_SECRET : '';
$req_token  = $_GET['token'] ?? ($_SERVER['HTTP_X_CRON_TOKEN'] ?? '');

if (!$is_cli && (!$cron_token || $req_token !== $cron_token)) {
    http_response_code(403);
    echo json_encode(['ok'=>false,'error'=>'Forbidden']);
    exit;
}

header('Content-Type: application/json');

$pdo     = dm_db();
$clients = $pdo->query("SELECT id, name FROM dm_clients WHERE active=1")->fetchAll(PDO::FETCH_ASSOC);

$results      = [];
$total_applied = 0;
$base_url     = defined('APP_URL') ? rtrim(APP_URL,'/') : 'https://dimark.co/supercerebro';

foreach ($clients as $client) {
    $cid     = $client['id'];
    $raw_ctx = dm_get_credential($cid,'google','neg_context');
    $ctx     = $raw_ctx ? json_decode($raw_ctx,true) : [];

    if (!($ctx['trust']['auto_mode']??false)) continue;

    $url = "{$base_url}/api/google-ads.php?client_id={$cid}&action=auto_run&cron_token=" . urlencode($cron_token);
    $ch  = curl_init($url);
    curl_setopt_array($ch,[
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 120,
        CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2,
    ]);
    $raw = curl_exec($ch);
    $err = curl_errno($ch);
    curl_close($ch);

    $res = (!$err && $raw) ? (json_decode($raw,true)??['ok'=>false,'error'=>'JSON inválido']) : ['ok'=>false,'error'=>'curl error '.$err];
    $results[$client['name']] = $res;
    if (!empty($res['applied'])) $total_applied += (int)$res['applied'];
}

echo json_encode([
    'ok'            => true,
    'ran_at'        => date('Y-m-d H:i'),
    'clients_run'   => count($results),
    'total_applied' => $total_applied,
    'detail'        => $results,
]);
