<?php
require __DIR__ . '/bootstrap.php';

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\Response;
use App\Core\Database;
use App\Services\NotificationService;
use App\Services\BackupService;

$user = Auth::requireUser();
$canManage = (in_array($user['role_name'] ?? '', ['super_admin','event_manager'], true) || Auth::hasPermission('notifications.manage', $user) || Auth::hasPermission('backups.manage', $user));
if (!$canManage) {
    Response::error('You do not have permission to manage notifications.', 403);
}

$input = request_input();
$method = $_SERVER['REQUEST_METHOD'];
$action = $input['action'] ?? 'overview';
$svc = new NotificationService();

if ($method === 'GET' && $action === 'overview') {
    $logs = [];
    $backups = [];
    try {
        $pdo = Database::connection();
        $logs = $pdo->query('SELECT * FROM notification_email_logs ORDER BY created_at DESC, id DESC LIMIT 80')->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable) {
        $logs = [];
    }

    try {
        $backups = (new BackupService())->listBackups();
    } catch (Throwable) {
        $backups = [];
    }

    Response::ok([
        'settings' => [
            'email_notifications_enabled' => (int)$svc->setting('email_notifications_enabled', '1'),
            'email_admin_recipients' => $svc->setting('email_admin_recipients', ''),
            'email_footer_text' => $svc->setting('email_footer_text', 'This is an automated notification from Pyrk Walking Club.'),
            'db_backup_enabled' => (int)$svc->setting('db_backup_enabled', '1'),
            'db_backup_retention_days' => (int)$svc->setting('db_backup_retention_days', '30'),
            'db_backup_path' => $svc->setting('db_backup_path', ''),
            'mail_driver' => $svc->effectiveMailConfig()['driver'] ?? 'log',
            'mail_from_email' => $svc->effectiveMailConfig()['from_email'] ?? '',
            'mail_from_name' => $svc->effectiveMailConfig()['from_name'] ?? '',
            'smtp_host' => $svc->effectiveMailConfig()['smtp']['host'] ?? '',
            'smtp_port' => $svc->effectiveMailConfig()['smtp']['port'] ?? 587,
            'smtp_username' => $svc->effectiveMailConfig()['smtp']['username'] ?? '',
            'smtp_password_saved' => $svc->effectiveMailConfig()['smtp']['password'] !== '',
            'smtp_encryption' => $svc->effectiveMailConfig()['smtp']['encryption'] ?? 'tls',
        ],
        'admin_recipients' => $svc->adminRecipients(),
        'events' => $svc->eventCatalog(),
        'logs' => $logs,
        'backups' => $backups,
    ]);
}

if ($method === 'POST' && $action === 'save_settings') {
    Csrf::validateFromRequest();

    $svc->saveSetting('email_notifications_enabled', !empty($input['email_notifications_enabled']) ? '1' : '0');
    $svc->saveSetting('email_admin_recipients', trim((string)($input['email_admin_recipients'] ?? '')));
    $svc->saveSetting('email_footer_text', trim((string)($input['email_footer_text'] ?? 'This is an automated notification from Pyrk Walking Club.')));
    $svc->saveSetting('db_backup_enabled', !empty($input['db_backup_enabled']) ? '1' : '0');
    $svc->saveSetting('db_backup_retention_days', (string)max(1, (int)($input['db_backup_retention_days'] ?? 30)));
    $svc->saveSetting('db_backup_path', trim((string)($input['db_backup_path'] ?? '')));

    $driver = (string)($input['mail_driver'] ?? 'log');
    if (!in_array($driver, ['log', 'mail', 'smtp'], true)) $driver = 'log';
    $svc->saveSetting('mail_driver', $driver);
    $svc->saveSetting('mail_from_email', trim((string)($input['mail_from_email'] ?? '')));
    $svc->saveSetting('mail_from_name', trim((string)($input['mail_from_name'] ?? 'Pyrk')));
    $svc->saveSetting('smtp_host', trim((string)($input['smtp_host'] ?? '')));
    $svc->saveSetting('smtp_port', (string)max(1, (int)($input['smtp_port'] ?? 587)));
    $svc->saveSetting('smtp_username', trim((string)($input['smtp_username'] ?? '')));
    if (array_key_exists('smtp_password', $input) && trim((string)$input['smtp_password']) !== '') {
        $svc->saveSetting('smtp_password', (string)$input['smtp_password']);
    }
    $encryption = (string)($input['smtp_encryption'] ?? 'tls');
    if (!in_array($encryption, ['tls', 'ssl', 'none'], true)) $encryption = 'tls';
    $svc->saveSetting('smtp_encryption', $encryption);

    $events = $input['events'] ?? [];
    if (is_string($events)) {
        $events = json_decode($events, true) ?: [];
    }

    if (is_array($events)) {
        foreach ($events as $event) {
            if (!is_array($event) || empty($event['event_key'])) continue;
            $svc->saveEventSettings(
                (string)$event['event_key'],
                !empty($event['enabled']),
                !empty($event['notify_admin']),
                !empty($event['notify_user'])
            );
        }
    }

    Response::ok([], 'Email and backup settings saved.');
}

if ($method === 'POST' && $action === 'test_email') {
    Csrf::validateFromRequest();
    $email = trim((string)($input['email'] ?? ''));
    if ($email === '') {
        $recipients = $svc->adminRecipients();
        $email = $recipients[0]['email'] ?? '';
    }
    $result = $svc->testEmail($email);
    $status = (string)($result['status'] ?? 'failed');
    if ($status === 'sent') {
        Response::ok(['result' => $result], 'Test email sent. Check the inbox.');
    }
    if ($status === 'logged') {
        Response::ok(['result' => $result], 'Test email was logged only. Set Mail driver to SMTP or PHP mail and save settings to deliver real emails.');
    }
    if ($status === 'disabled') {
        Response::ok(['result' => $result], 'Email notifications are disabled. Enable them to send automatic emails.');
    }
    Response::ok(['result' => $result], 'Test email failed: ' . ($result['error'] ?? 'Unknown error'));
}

if ($method === 'POST' && $action === 'create_backup') {
    Csrf::validateFromRequest();
    if ((int)$svc->setting('db_backup_enabled', '1') !== 1) {
        Response::error('Database backups are turned off in settings.');
    }
    try {
        $backup = (new BackupService())->createDatabaseBackup((int)$user['id']);
        Response::ok(['backup' => $backup], 'Database backup created.');
    } catch (Throwable $e) {
        Response::error('Backup failed: ' . $e->getMessage());
    }
}

Response::error('Unsupported notification action.', 404);
