<?php
// api/automations.php — CRUD de automatizaciones por cliente
// GET  ?action=list&client_id=N         → lista reglas del cliente
// GET  ?action=trigger_log&client_id=N  → historial de disparos
// POST ?action=create                   → nueva regla
// POST ?action=update                   → editar regla
// POST ?action=toggle                   → pausar / activar regla
// POST ?action=delete                   → eliminar regla

header('Content-Type: application/json');
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../auth.php';
require_once __DIR__ . '/../credentials.php';

dm_require_login();
if (!dm_is_admin()) { echo json_encode(['ok'=>false,'error'=>'No autorizado']); exit; }
if (!$pdo)          { echo json_encode(['ok'=>false,'error'=>'Sin BD']);         exit; }

// ── Auto-crear tablas ────────────────────────────────────────────────────────
$pdo->exec("
    CREATE TABLE IF NOT EXISTS dm_automations (
        id                INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        client_id         INT UNSIGNED NOT NULL,
        name              VARCHAR(100) NOT NULL,
        condition_type    VARCHAR(40)  NOT NULL,
        condition_params  JSON         NOT NULL,
        action_type       VARCHAR(40)  NOT NULL,
        action_params     JSON         NOT NULL,
        frequency         ENUM('hourly','daily','weekly') NOT NULL DEFAULT 'daily',
        status            ENUM('active','paused') NOT NULL DEFAULT 'active',
        last_triggered_at DATETIME     NULL,
        trigger_count     INT UNSIGNED NOT NULL DEFAULT 0,
        created_at        DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_client (client_id),
        INDEX idx_status  (status)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");
$pdo->exec("
    CREATE TABLE IF NOT EXISTS dm_automation_log (
        id            INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        automation_id INT UNSIGNED NOT NULL,
        client_id     INT UNSIGNED NOT NULL,
        result        ENUM('triggered','skipped','error') NOT NULL DEFAULT 'triggered',
        detail        TEXT,
        triggered_at  DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_auto   (automation_id),
        INDEX idx_client (client_id),
        INDEX idx_ts     (triggered_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");

$input     = json_decode(file_get_contents('php://input'), true) ?? [];
$action    = $_GET['action'] ?? ($input['action'] ?? 'list');
$client_id = (int)($_GET['client_id'] ?? $input['client_id'] ?? 0);

if (in_array($action, ['create','update','delete','toggle'])) dm_csrf_verify();

// ── LIST ─────────────────────────────────────────────────────────────────────
if ($action === 'list') {
    if (!$client_id) { echo json_encode(['ok'=>false,'error'=>'client_id requerido']); exit; }
    $stmt = $pdo->prepare("SELECT * FROM dm_automations WHERE client_id=? ORDER BY created_at DESC");
    $stmt->execute([$client_id]);
    echo json_encode(['ok'=>true,'automations'=>$stmt->fetchAll(PDO::FETCH_ASSOC)]);
    exit;
}

// ── TRIGGER LOG ──────────────────────────────────────────────────────────────
if ($action === 'trigger_log') {
    if (!$client_id) { echo json_encode(['ok'=>false,'error'=>'client_id requerido']); exit; }
    $stmt = $pdo->prepare("
        SELECT l.*, a.name AS automation_name
          FROM dm_automation_log l
          JOIN dm_automations a ON a.id = l.automation_id
         WHERE l.client_id = ?
         ORDER BY l.triggered_at DESC
         LIMIT 40
    ");
    $stmt->execute([$client_id]);
    echo json_encode(['ok'=>true,'logs'=>$stmt->fetchAll(PDO::FETCH_ASSOC)]);
    exit;
}

// ── CREATE ───────────────────────────────────────────────────────────────────
if ($action === 'create') {
    if (!$client_id) { echo json_encode(['ok'=>false,'error'=>'client_id requerido']); exit; }
    $name      = trim($input['name']            ?? '');
    $ctype     = trim($input['condition_type']  ?? '');
    $cparams   = $input['condition_params']      ?? [];
    $atype     = trim($input['action_type']     ?? '');
    $aparams   = $input['action_params']          ?? [];
    $frequency = in_array($input['frequency'] ?? '', ['hourly','daily','weekly'])
                 ? $input['frequency'] : 'daily';

    if (!$name || !$ctype || !$atype) {
        echo json_encode(['ok'=>false,'error'=>'Nombre, condición y acción son obligatorios']); exit;
    }

    $pdo->prepare("
        INSERT INTO dm_automations
            (client_id, name, condition_type, condition_params, action_type, action_params, frequency)
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ")->execute([
        $client_id, $name, $ctype,
        json_encode($cparams), $atype, json_encode($aparams), $frequency,
    ]);

    if (function_exists('dm_activity'))
        dm_activity($client_id, 'automation_created', "Automatización creada: {$name}");

    echo json_encode(['ok'=>true,'id'=>(int)$pdo->lastInsertId()]);
    exit;
}

// ── UPDATE ───────────────────────────────────────────────────────────────────
if ($action === 'update') {
    $id = (int)($input['id'] ?? 0);
    if (!$id) { echo json_encode(['ok'=>false,'error'=>'id requerido']); exit; }
    $fields = []; $vals = [];
    foreach (['name','condition_type','action_type','frequency'] as $f) {
        if (isset($input[$f])) { $fields[] = "{$f}=?"; $vals[] = $input[$f]; }
    }
    foreach (['condition_params','action_params'] as $f) {
        if (isset($input[$f])) { $fields[] = "{$f}=?"; $vals[] = json_encode($input[$f]); }
    }
    if (empty($fields)) { echo json_encode(['ok'=>false,'error'=>'Nada que actualizar']); exit; }
    $vals[] = $id;
    $pdo->prepare("UPDATE dm_automations SET ".implode(',',$fields)." WHERE id=?")->execute($vals);
    echo json_encode(['ok'=>true]);
    exit;
}

// ── TOGGLE ───────────────────────────────────────────────────────────────────
if ($action === 'toggle') {
    $id = (int)($input['id'] ?? 0);
    if (!$id) { echo json_encode(['ok'=>false,'error'=>'id requerido']); exit; }
    $row = $pdo->prepare("SELECT status, name FROM dm_automations WHERE id=?");
    $row->execute([$id]);
    $r = $row->fetch(PDO::FETCH_ASSOC);
    if (!$r) { echo json_encode(['ok'=>false,'error'=>'No encontrada']); exit; }
    $new = $r['status'] === 'active' ? 'paused' : 'active';
    $pdo->prepare("UPDATE dm_automations SET status=? WHERE id=?")->execute([$new,$id]);
    echo json_encode(['ok'=>true,'status'=>$new]);
    exit;
}

// ── DELETE ───────────────────────────────────────────────────────────────────
if ($action === 'delete') {
    $id = (int)($input['id'] ?? 0);
    if (!$id) { echo json_encode(['ok'=>false,'error'=>'id requerido']); exit; }
    $pdo->prepare("DELETE FROM dm_automations WHERE id=?")->execute([$id]);
    $pdo->prepare("DELETE FROM dm_automation_log WHERE automation_id=?")->execute([$id]);
    echo json_encode(['ok'=>true]);
    exit;
}

// ── GET SETTINGS ─────────────────────────────────────────────────────────────
if ($action === 'get_settings') {
    // Auto-crear tabla dm_settings si no existe
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS dm_settings (
            `key`   VARCHAR(60) NOT NULL PRIMARY KEY,
            `value` TEXT        NOT NULL DEFAULT '',
            updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
    $keys = ['notif_window_start','notif_window_end','notif_daily_hour',
             'notif_weekly_day','notif_weekly_hour','notif_digest_mode'];
    $rows = $pdo->query(
        "SELECT `key`,`value` FROM dm_settings WHERE `key` IN ('".implode("','",$keys)."')"
    )->fetchAll(PDO::FETCH_KEY_PAIR);

    $defaults = [
        'notif_window_start' => '8',
        'notif_window_end'   => '20',
        'notif_daily_hour'   => '9',
        'notif_weekly_day'   => '1',
        'notif_weekly_hour'  => '9',
        'notif_digest_mode'  => '0',
    ];
    $settings = [];
    foreach ($defaults as $k => $def) {
        $settings[$k] = $rows[$k] ?? $def;
    }
    echo json_encode(['ok'=>true,'settings'=>$settings]);
    exit;
}

// ── SAVE SETTINGS ────────────────────────────────────────────────────────────
if ($action === 'save_settings') {
    dm_csrf_verify();
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS dm_settings (
            `key`   VARCHAR(60) NOT NULL PRIMARY KEY,
            `value` TEXT        NOT NULL DEFAULT '',
            updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
    $allowed = ['notif_window_start','notif_window_end','notif_daily_hour',
                'notif_weekly_day','notif_weekly_hour','notif_digest_mode'];
    $saved = 0;
    foreach ($allowed as $k) {
        if (!isset($input[$k])) continue;
        $v = (string)$input[$k];
        $pdo->prepare(
            "INSERT INTO dm_settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?"
        )->execute([$k, $v, $v]);
        $saved++;
    }
    echo json_encode(['ok'=>true,'saved'=>$saved]);
    exit;
}

// ── TEST NOW — evalúa condición en tiempo real (sin ejecutar acción) ──────────
if ($action === 'test_now') {
    $id = (int)($_GET['id'] ?? $input['id'] ?? 0);
    if (!$id) { echo json_encode(['ok'=>false,'error'=>'id requerido']); exit; }

    $auto_row = $pdo->prepare("SELECT * FROM dm_automations WHERE id=?");
    $auto_row->execute([$id]);
    $auto = $auto_row->fetch(PDO::FETCH_ASSOC);
    if (!$auto) { echo json_encode(['ok'=>false,'error'=>'Regla no encontrada']); exit; }

    $cid     = (int)$auto['client_id'];
    $cparams = json_decode($auto['condition_params'], true) ?? [];
    $d14     = date('Y-m-d', strtotime('-14 days'));
    $d7      = date('Y-m-d', strtotime('-7 days'));

    // Cargar historial de métricas
    $stmt = $pdo->prepare(
        "SELECT service, metric_date, data FROM dm_metrics_history
          WHERE client_id=? AND metric_date>=? ORDER BY service, metric_date ASC"
    );
    $stmt->execute([$cid, $d14]);
    $h = [];
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $h[$row['service']][$row['metric_date']] = json_decode($row['data'], true);
    }

    $met    = false;
    $detail = 'Condición no cumplida';

    switch ($auto['condition_type']) {
        case 'meta_spend_zero':
            $days  = max(1, (int)($cparams['days'] ?? 3));
            $since = date('Y-m-d', strtotime("-{$days} days"));
            $mh    = array_filter($h['meta'] ?? [], fn($d) => $d >= $since, ARRAY_FILTER_USE_KEY);
            if (array_sum(array_column($mh, 'spend')) <= 0 && count($mh) > 0) {
                $met = true; $detail = "Meta sin inversión en los últimos {$days} días";
            } else {
                $detail = "Meta tiene inversión activa (OK)";
            }
            break;
        case 'meta_campaigns_paused':
            $mh7    = array_filter($h['meta'] ?? [], fn($d) => $d >= $d7, ARRAY_FILTER_USE_KEY);
            $active = array_sum(array_column($mh7, 'campaigns_active'));
            if (count($mh7) > 0 && $active === 0) {
                $met = true; $detail = "Meta: todas las campañas pausadas";
            } else {
                $detail = "Meta tiene {$active} campaña(s) activa(s) (OK)";
            }
            break;
        case 'meta_frequency_high':
            $threshold = (float)($cparams['threshold'] ?? 3.0);
            $mh7       = array_filter($h['meta'] ?? [], fn($d) => $d >= $d7, ARRAY_FILTER_USE_KEY);
            $freq_vals = array_filter(array_column($mh7, 'frequency'), fn($v) => $v !== null && $v > 0);
            if (count($freq_vals) > 0) {
                $avg = array_sum($freq_vals) / count($freq_vals);
                if ($avg > $threshold) { $met = true; $detail = "Frecuencia promedio ".round($avg,2)." > {$threshold}"; }
                else $detail = "Frecuencia promedio ".round($avg,2)." ≤ {$threshold} (OK)";
            } else {
                $detail = "Sin datos de frecuencia en historial";
            }
            break;
        case 'meta_cpa_above':
            $threshold = (float)($cparams['threshold'] ?? 50);
            $mh7       = array_filter($h['meta'] ?? [], fn($d) => $d >= $d7, ARRAY_FILTER_USE_KEY);
            $sp        = array_sum(array_column($mh7, 'spend'));
            $cv        = array_sum(array_column($mh7, 'conversions'));
            if ($sp > 0 && $cv > 0) {
                $cpa = $sp / $cv;
                if ($cpa > $threshold) { $met = true; $detail = "Meta CPA \$".number_format($cpa,2)." > \${$threshold}"; }
                else $detail = "Meta CPA \$".number_format($cpa,2)." ≤ \${$threshold} (OK)";
            } else {
                $detail = "Datos insuficientes (spend o conversiones en 0)";
            }
            break;
        case 'google_is_below':
            $threshold = (float)($cparams['threshold'] ?? 30);
            $gh7       = array_filter($h['google'] ?? [], fn($d) => $d >= $d7, ARRAY_FILTER_USE_KEY);
            $is_vals   = array_filter(array_column($gh7,'search_impression_share'), fn($v) => $v !== null && is_numeric($v));
            if (count($is_vals) > 0) {
                $avg = array_sum($is_vals) / count($is_vals);
                if ($avg < $threshold) { $met = true; $detail = "Google IS ".round($avg,1)."% < {$threshold}%"; }
                else $detail = "Google IS ".round($avg,1)."% ≥ {$threshold}% (OK)";
            } else {
                $detail = "Sin datos de IS en historial";
            }
            break;
        case 'google_spend_zero':
            $days  = max(1, (int)($cparams['days'] ?? 3));
            $since = date('Y-m-d', strtotime("-{$days} days"));
            $gh    = array_filter($h['google'] ?? [], fn($d) => $d >= $since, ARRAY_FILTER_USE_KEY);
            if (array_sum(array_column($gh, 'cost')) <= 0 && count($gh) > 0) {
                $met = true; $detail = "Google sin inversión en los últimos {$days} días";
            } else {
                $detail = "Google tiene inversión activa (OK)";
            }
            break;
        case 'google_cpa_above':
            $threshold = (float)($cparams['threshold'] ?? 50);
            $gh7       = array_filter($h['google'] ?? [], fn($d) => $d >= $d7, ARRAY_FILTER_USE_KEY);
            $cost      = array_sum(array_column($gh7, 'cost'));
            $conv      = array_sum(array_column($gh7, 'conversions'));
            if ($cost > 0 && $conv > 0) {
                $cpa = $cost / $conv;
                if ($cpa > $threshold) { $met = true; $detail = "Google CPA \$".number_format($cpa,2)." > \${$threshold}"; }
                else $detail = "Google CPA \$".number_format($cpa,2)." ≤ \${$threshold} (OK)";
            } else {
                $detail = "Datos insuficientes (cost o conversiones en 0)";
            }
            break;
        case 'google_conversions_zero':
            $days  = max(1, (int)($cparams['days'] ?? 7));
            $since = date('Y-m-d', strtotime("-{$days} days"));
            $gh    = array_filter($h['google'] ?? [], fn($d) => $d >= $since, ARRAY_FILTER_USE_KEY);
            if (count($gh) > 0 && array_sum(array_column($gh, 'conversions')) == 0) {
                $met = true; $detail = "Google sin conversiones en los últimos {$days} días";
            } else {
                $total_conv = array_sum(array_column($gh, 'conversions'));
                $detail = "Google tiene {$total_conv} conversión(es) en {$days} días (OK)";
            }
            break;
        case 'seo_clicks_drop':
            $threshold = (float)($cparams['threshold'] ?? 20);
            $sh        = $h['gsc'] ?? [];
            ksort($sh);
            $all_dates = array_keys($sh);
            $n         = count($all_dates);
            if ($n >= 4) {
                $mid  = (int)floor($n / 2);
                $prev = array_sum(array_map(fn($d) => (int)($sh[$d]['clicks'] ?? 0), array_slice($all_dates,0,$mid)));
                $curr = array_sum(array_map(fn($d) => (int)($sh[$d]['clicks'] ?? 0), array_slice($all_dates,$mid)));
                if ($prev > 0) {
                    $pct = ($curr - $prev) / $prev * 100;
                    if ($pct <= -$threshold) { $met = true; $detail = "SEO caída ".round($pct,1)."% en clics (umbral -{$threshold}%)"; }
                    else $detail = "SEO cambio ".round($pct,1)."% en clics (OK)";
                }
            } else {
                $detail = "Historial SEO insuficiente (necesita ≥4 días)";
            }
            break;
        case 'semaforo_red':
            $red = [];
            $mh7 = array_filter($h['meta'] ?? [], fn($d) => $d >= $d7, ARRAY_FILTER_USE_KEY);
            if (!empty($mh7) && (array_sum(array_column($mh7,'spend')) <= 0 || array_sum(array_column($mh7,'campaigns_active')) === 0)) $red[] = 'Meta';
            $gh7 = array_filter($h['google'] ?? [], fn($d) => $d >= $d7, ARRAY_FILTER_USE_KEY);
            if (!empty($gh7)) {
                $is_v = array_filter(array_column($gh7,'search_impression_share'), fn($v) => is_numeric($v));
                $is_a = count($is_v) > 0 ? array_sum($is_v)/count($is_v) : null;
                if (($is_a !== null && $is_a < 30) || ($is_a === null && array_sum(array_column($gh7,'cost')) <= 0)) $red[] = 'Google';
            }
            $sh = $h['gsc'] ?? []; ksort($sh); $all_d = array_keys($sh); $nn = count($all_d);
            if ($nn >= 4) {
                $mid  = (int)floor($nn/2);
                $prev = array_sum(array_map(fn($d) => (int)($sh[$d]['clicks']??0), array_slice($all_d,0,$mid)));
                $curr = array_sum(array_map(fn($d) => (int)($sh[$d]['clicks']??0), array_slice($all_d,$mid)));
                if ($prev > 0 && ($curr-$prev)/$prev*100 <= -20) $red[] = 'SEO';
            }
            if (!empty($red)) { $met = true; $detail = "Semáforo en rojo: ".implode(', ',$red); }
            else $detail = "Todos los canales en verde/amarillo (OK)";
            break;
        default:
            $detail = "Condición '{$auto['condition_type']}' no reconocida";
    }

    echo json_encode(['ok'=>true, 'met'=>$met, 'detail'=>$detail,
        'condition_type'=>$auto['condition_type'], 'client_id'=>$cid]);
    exit;
}

echo json_encode(['ok'=>false,'error'=>'Acción no reconocida']);
