<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../app/helpers/rbac.php';
require_once __DIR__ . '/../app/helpers/api_security.php';
require_once __DIR__ . '/../app/helpers/alerts.php';

header('Content-Type: application/json; charset=utf-8');

requireApiPermission('user.manage');
enforceCsrfForUnsafeRequest();

$action = $_GET['action'] ?? 'list';

try {
    if ($action === 'list') {
        $status = trim((string)($_GET['status'] ?? ''));
        $search = trim((string)($_GET['search'] ?? ''));
        $conditions = ['deleted_at IS NULL'];
        $params = [];
        if ($status !== '') {
            $conditions[] = 'status = :status';
            $params['status'] = $status;
        }
        if ($search !== '') {
            $q = '%' . $search . '%';
            $conditions[] = '(event_key LIKE :q1 OR channel LIKE :q2 OR recipient LIKE :q3)';
            $params['q1'] = $q; $params['q2'] = $q; $params['q3'] = $q;
        }
        $where = 'WHERE ' . implode(' AND ', $conditions);
        $stmt = $pdo->prepare("
            SELECT id, event_key, channel, user_id, recipient, subject, status,
                   attempts, next_attempt_at, delivered_at, provider_response, created_at
            FROM alert_delivery_logs
            {$where}
            ORDER BY id DESC
            LIMIT 100
        ");
        $stmt->execute($params);
        apiRespond(['status' => 'success', 'data' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
    }

    if ($action === 'settings') {
        $config = require __DIR__ . '/../config/alerts.php';
        apiRespond(['status' => 'success', 'data' => [
            'email_enabled' => (bool)$config['email_enabled'],
            'sms_enabled' => (bool)$config['sms_enabled'],
            'sms_provider' => $config['sms_provider'],
            'sms_sender' => $config['sms_sender'],
            'sms_webhook_url' => $config['sms_webhook_url'] ?? '',
            'app_url' => $config['app_url'],
        ]]);
    }

    if ($action === 'retry') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id <= 0) {
            apiRespond(['status' => 'error', 'message' => 'Invalid delivery id'], 422);
        }
        apiRespond(alertRetryDelivery($pdo, $id));
    }

    apiRespond(['status' => 'error', 'message' => 'Invalid action'], 404);
} catch (Throwable $e) {
    apiRespond(['status' => 'error', 'message' => $e->getMessage()], 500);
}
