<?php
namespace App\Controllers;

use App\Core\Database;

class NotificationSettingsController
{
    protected function db()
    {
        return Database::getInstance();
    }

    private function startSession(): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }
    }

    private function requireLogin(): void
    {
        $this->startSession();

        if (empty($_SESSION['user_id'])) {
            header("Location: /easychair/login");
            exit;
        }
    }

    private function role(): string
    {
        return (string)($_SESSION['conference_role'] ?? $_SESSION['role'] ?? $_SESSION['user_role'] ?? '');
    }

    private function ensureDefaults(): void
    {
        $conferenceId = (int)($_SESSION['conference_id'] ?? 0);
        $userId = (int)($_SESSION['user_id'] ?? 0);

        if ($conferenceId <= 0 || $userId <= 0) {
            return;
        }

        $stmt = $this->db()->prepare("SELECT org_id FROM conferences WHERE id=? LIMIT 1");
        $stmt->execute([$conferenceId]);
        $orgId = (int)$stmt->fetchColumn();

        foreach (['workflow','broadcast','review','mail','system'] as $type) {
            $stmt = $this->db()->prepare("
                INSERT INTO user_notification_preferences
                (user_id, org_id, conference_id, notification_type, in_app_enabled, email_enabled, digest_enabled, digest_frequency)
                VALUES (?, ?, ?, ?, 1, 1, 0, 'none')
                ON DUPLICATE KEY UPDATE updated_at=updated_at
            ");
            $stmt->execute([$userId, $orgId ?: null, $conferenceId, $type]);
        }
    }

    public function index()
    {
        $this->requireLogin();
        $this->ensureDefaults();

        $conferenceId = (int)($_SESSION['conference_id'] ?? 0);
        $userId = (int)$_SESSION['user_id'];

        $stmt = $this->db()->prepare("
            SELECT p.*, c.short_name
            FROM user_notification_preferences p
            LEFT JOIN conferences c ON c.id=p.conference_id
            WHERE p.user_id=?
              AND (
                    p.conference_id=?
                    OR p.conference_id IS NULL
              )
            ORDER BY p.conference_id DESC, p.notification_type
        ");
        $stmt->execute([$userId, $conferenceId]);
        $preferences = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        ob_start();
        require BASE_PATH . '/app/views/notifications/settings.php';
        $content = ob_get_clean();

        $role = $this->role();

        if (in_array($role, ['super_admin','org_admin','admin','organizer','conference_chair','track_chair'], true)) {
            require BASE_PATH . '/app/views/layouts/admin_layout.php';
        } elseif ($role === 'reviewer') {
            require BASE_PATH . '/app/views/layouts/reviewer_layout.php';
        } else {
            require BASE_PATH . '/app/views/layouts/author_layout.php';
        }
    }

    public function save()
    {
        $this->requireLogin();

        $prefs = $_POST['prefs'] ?? [];
        $userId = (int)$_SESSION['user_id'];

        foreach ($prefs as $id => $p) {
            $id = (int)$id;

            $frequency = (string)($p['digest_frequency'] ?? 'none');
            if (!in_array($frequency, ['none','daily','weekly'], true)) {
                $frequency = 'none';
            }

            $mutedUntil = trim((string)($p['muted_until'] ?? ''));
            if ($mutedUntil === '') {
                $mutedUntil = null;
            }

            $stmt = $this->db()->prepare("
                UPDATE user_notification_preferences
                SET in_app_enabled=?,
                    email_enabled=?,
                    digest_enabled=?,
                    digest_frequency=?,
                    muted_until=?,
                    updated_at=NOW()
                WHERE id=?
                  AND user_id=?
            ");
            $stmt->execute([
                !empty($p['in_app_enabled']) ? 1 : 0,
                !empty($p['email_enabled']) ? 1 : 0,
                !empty($p['digest_enabled']) ? 1 : 0,
                $frequency,
                $mutedUntil,
                $id,
                $userId
            ]);
        }

        $_SESSION['flash_success'] = 'Notification preferences saved.';
        header("Location: /easychair/notification-settings?saved=1");
        exit;
    }
}
