<?php
declare(strict_types=1);

if (PHP_SAPI !== 'cli') {
    $server_secret = trim((string) getenv('MAINPP_PUSH_SECRET'));
    $request_secret = trim((string) ($_SERVER['HTTP_X_MAINPP_PUSH_SECRET'] ?? ''));
    if ($server_secret === '' || !hash_equals($server_secret, $request_secret)) {
        http_response_code(403);
        exit('Forbidden');
    }
}

require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/push_service.php';

$query = mysqli_query(
    $conn,
    "SELECT ce.id, ce.user_id, ce.event_type, ce.title, ce.start_at
     FROM calendar_events ce
     WHERE ce.deleted_at IS NULL
       AND ce.event_type IN ('task', 'meeting')
       AND ce.start_at BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 15 MINUTE)
       AND NOT EXISTS (
         SELECT 1 FROM push_notifications pn
         WHERE pn.user_id = ce.user_id
           AND pn.notification_type = 'calendar_reminder'
           AND pn.entity_id = CAST(ce.id AS CHAR)
           AND pn.status IN ('processing', 'sent')
       )
     ORDER BY ce.start_at ASC"
);

$processed = 0;
while ($event = $query ? mysqli_fetch_assoc($query) : null) {
    $event_id = (int) ($event['id'] ?? 0);
    $user_id = (int) ($event['user_id'] ?? 0);
    if ($event_id <= 0 || $user_id <= 0) continue;

    $type = (string) ($event['event_type'] ?? 'event');
    $title = $type === 'meeting' ? 'Meeting akan bermula' : 'Task akan bermula';
    $body = trim((string) ($event['title'] ?? 'Aktiviti')) . ' pada ' . date('g:i A', strtotime((string) $event['start_at']));

    $insert = mysqli_prepare(
        $conn,
        "INSERT INTO push_notifications
         (user_id, title, body, notification_type, entity_id, payload_json, status, attempts)
         VALUES (?, ?, ?, 'calendar_reminder', ?, ?, 'processing', 1)"
    );
    $entity_id = (string) $event_id;
    $payload = json_encode(['type' => $type, 'event_id' => $event_id, 'route' => 'calendar']);
    mysqli_stmt_bind_param($insert, 'issss', $user_id, $title, $body, $entity_id, $payload);
    if (!mysqli_stmt_execute($insert)) continue;
    $notification_id = (int) mysqli_insert_id($conn);

    $result = sendMainppPush($conn, $user_id, $title, $body, [
        'type' => $type,
        'event_id' => $event_id,
        'route' => 'calendar',
    ]);
    $status = !empty($result['success']) ? 'sent' : 'failed';
    $last_error = !empty($result['success']) ? null : 'Tiada peranti aktif atau penghantaran FCM gagal.';
    $update = mysqli_prepare(
        $conn,
        'UPDATE push_notifications SET status = ?, last_error = ?, sent_at = IF(? = "sent", NOW(), NULL) WHERE id = ?'
    );
    mysqli_stmt_bind_param($update, 'sssi', $status, $last_error, $status, $notification_id);
    mysqli_stmt_execute($update);
    $processed++;
}

header('Content-Type: application/json; charset=utf-8');
echo json_encode(['success' => true, 'processed' => $processed], JSON_UNESCAPED_UNICODE);
