<?php
// api/public-report-token.php — Gestión de tokens para reportes públicos compartibles
header('Content-Type: application/json');
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../auth.php';
dm_require_login();
dm_csrf_verify();

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

if (!$client_id) { echo json_encode(['ok'=>false,'error'=>'client_id requerido']); exit; }
dm_require_client_access($client_id);

// Auto-crear tabla si no existe
$pdo->exec("CREATE TABLE IF NOT EXISTS dm_report_tokens (
    id INT AUTO_INCREMENT PRIMARY KEY,
    report_id INT NOT NULL,
    client_id INT NOT NULL,
    token VARCHAR(64) NOT NULL UNIQUE,
    expires_at DATETIME NOT NULL,
    created_at DATETIME NOT NULL DEFAULT NOW(),
    INDEX idx_token (token),
    INDEX idx_report (report_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

if ($action === 'create') {
    if (!$report_id) { echo json_encode(['ok'=>false,'error'=>'report_id requerido']); exit; }

    // Verificar que el reporte pertenece al cliente
    $check = $pdo->prepare("SELECT id FROM dm_reports WHERE id=? AND client_id=? LIMIT 1");
    $check->execute([$report_id, $client_id]);
    if (!$check->fetch()) { echo json_encode(['ok'=>false,'error'=>'Reporte no encontrado']); exit; }

    // Reutilizar token existente si no expiró
    $existing = $pdo->prepare("SELECT token FROM dm_report_tokens WHERE report_id=? AND expires_at > NOW() LIMIT 1");
    $existing->execute([$report_id]);
    $row = $existing->fetch(PDO::FETCH_ASSOC);

    if ($row) {
        $token = $row['token'];
    } else {
        $token = bin2hex(random_bytes(32));
        $expires = date('Y-m-d H:i:s', strtotime('+30 days'));
        $pdo->prepare("INSERT INTO dm_report_tokens (report_id, client_id, token, expires_at) VALUES (?,?,?,?)")
            ->execute([$report_id, $client_id, $token, $expires]);
    }

    $base = rtrim(defined('APP_URL') ? APP_URL : 'https://dimark.co/supercerebro', '/');
    echo json_encode(['ok'=>true,'token'=>$token,'url'=>$base.'/public-report.php?token='.$token]);

} elseif ($action === 'revoke') {
    if (!$report_id) { echo json_encode(['ok'=>false,'error'=>'report_id requerido']); exit; }
    $pdo->prepare("DELETE FROM dm_report_tokens WHERE report_id=? AND client_id=?")->execute([$report_id, $client_id]);
    echo json_encode(['ok'=>true]);

} else {
    echo json_encode(['ok'=>false,'error'=>'Acción desconocida']);
}
