<?php
// Riceve payload di risposta dal calendario e invia push 1-to-1 (FCM o VAPID)
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
date_default_timezone_set('Europe/Rome');

function out($payload, $code = 200) {
    http_response_code($code);
    echo json_encode($payload);
    exit;
}

$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
if (!is_array($data) || empty($data)) { $data = $_POST ?: $_GET; }
if (!$data) {
    out(['success' => false, 'message' => 'Payload non valido'], 400);
}

$clienteId = trim((string)($data["cliente_id"] ?? $data["cid"] ?? $data["device_id"] ?? $data["device_id_base"] ?? $data["user_id"] ?? $data["telefono"] ?? ""));
$message  = $data['message'] ?? '';
$source   = $data['source'] ?? 'calendar_reply';

if ($message === '' || $clienteId === '') {
    out(['success' => false, 'message' => 'Campi obbligatori mancanti (message e cliente_id)'], 400);
}

$userId   = $clienteId;
$telefono = $data['telefono'] ?? '';

// Traccia il payload in un file di log dedicato
$logDir = __DIR__ . '//var/www/debug_logs';
if (!is_dir($logDir)) {
    @mkdir($logDir, 0777, true);
    @chmod($logDir, 0777);
}
$logFile = $logDir . '/trace_reply.log';
if (!is_writable($logDir)) {
    $logFile = __DIR__ . '/api_debug.log';
}
$trace = [
    'ts' => date('Y-m-d H:i:s'),
    'user_id' => $userId,
    'telefono' => $telefono,
    'message' => $message,
    'source' => $source
];
file_put_contents($logFile, "[TRACE_REPLY] " . json_encode($trace) . PHP_EOL, FILE_APPEND);

// Recupera token/subscription dal DB usando device_id = cliente_id
$cfgPath = dirname(__DIR__) . '/config/vapid.json';
$dbFile = __DIR__ . '/push_subscriptions.db';
if (file_exists($cfgPath)) {
    $cfg = json_decode(file_get_contents($cfgPath), true);
    if (!empty($cfg['db_file'])) {
        $dbFile = __DIR__ . '/' . $cfg['db_file'];
    }
}

$subRow = null;
try {
    $db = new PDO('sqlite:' . $dbFile);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    // Assicurati che esista la colonna fcm_token
    $cols = $db->query("PRAGMA table_info(subscriptions)")->fetchAll(PDO::FETCH_ASSOC);
    $colNames = array_map(fn($c) => $c['name'], $cols);
    if (!in_array('fcm_token', $colNames, true)) {
        $db->exec("ALTER TABLE subscriptions ADD COLUMN fcm_token TEXT");
    }

    $stmt = $db->prepare("SELECT endpoint, p256dh, auth, fcm_token FROM subscriptions WHERE (device_id = :cid OR user_id = :cid OR telefono = :cid OR phone = :cid) AND trim(coalesce(fcm_token, '')) != '' ORDER BY id DESC LIMIT 1");
    $stmt->execute([':cid' => $clienteId]);
    $subRow = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    file_put_contents($logFile, "[TRACE_REPLY_ERR] DB: " . $e->getMessage() . PHP_EOL, FILE_APPEND);
    out(['success' => false, 'message' => 'Errore DB'], 500);
}

if (!$subRow) {
    out(['success' => false, 'message' => 'Nessun token trovato'], 400);
}

// 1) FCM se disponibile
if (!empty($subRow['fcm_token'])) {
    require_once __DIR__ . '/send_fcm_native.php';
    $res = sendFcmNotification($subRow['fcm_token'], 'Risposta dal calendario', $message, [
        'source' => $source,
        'reply' => true,
        'cliente_id' => $clienteId
    ]);
    if (!$res['success']) {
        out(['success' => false, 'message' => 'Errore invio push (FCM)', 'error' => $res['error'], 'http' => $res['http_code']], 500);
    }
    out(['success' => true, 'message' => 'Push inviata', 'channel' => 'fcm']);
}

// 2) Fallback VAPID con send_push_user.php
if (empty($subRow['endpoint']) || empty($subRow['p256dh']) || empty($subRow['auth'])) {
    out(['success' => false, 'message' => 'Nessun token trovato'], 400);
}

$pushPayload = [
    'user_id' => $clienteId,
    'telefono' => $telefono,
    'title' => 'Risposta dal calendario',
    'body' => $message,
    'data' => [
        'source' => $source,
        'reply' => true
    ],
    'endpoint' => $subRow['endpoint'],
    'p256dh' => $subRow['p256dh'],
    'auth' => $subRow['auth']
];

$proto = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = 'puschpromozioni.it';
$path = rtrim(dirname($_SERVER['REQUEST_URI']), '/');
$pushUrl = $proto . '://' . $host . $path . '/send_push_user.php';

$opts = [
    'http' => [
        'method' => 'POST',
        'header' => "Content-Type: application/json\r\n",
        'content' => json_encode($pushPayload),
        'timeout' => 10
    ]
];
$ctx = stream_context_create($opts);
$resp = @file_get_contents($pushUrl, false, $ctx);
$httpCode = 0;
if (isset($http_response_header)) {
    foreach ($http_response_header as $hdr) {
        if (preg_match('#HTTP/\\S+\\s+(\\d{3})#', $hdr, $m)) {
            $httpCode = (int)$m[1];
            break;
        }
    }
}

file_put_contents($logFile, "[TRACE_REPLY_SEND] channel=vapid url={$pushUrl} http={$httpCode} resp={$resp}\n", FILE_APPEND);

$respJson = json_decode($resp, true);
if ($resp === false || $httpCode >= 400) {
    out(['success' => false, 'message' => 'Errore invio push', 'http' => $httpCode, 'response' => $resp], 500);
}

out(['success' => true, 'message' => 'Push inviata', 'channel' => 'vapid', 'push_response' => $respJson]);
