<?php
namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/conference_scope.php';

use App\Core\Database;

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

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

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

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

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

        if (empty($_SESSION['conference_id'])) {
            header("Location: /easychair/select-conference");
            exit;
        }

        if (!in_array($this->role(), ['super_admin','org_admin','admin','organizer','conference_chair'], true)) {
            http_response_code(403);
            exit("Access denied.");
        }
    }

    private function conference(): array
    {
        $stmt = $this->db()->prepare("SELECT * FROM conferences WHERE id=? LIMIT 1");
        $stmt->execute([(int)$_SESSION['conference_id']]);
        $c = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$c) {
            exit("Conference not found.");
        }

        if ($this->role() !== 'super_admin' && (int)$c['org_id'] !== (int)($_SESSION['org_id'] ?? 0)) {
            http_response_code(403);
            exit("Invalid organization access.");
        }

        return $c;
    }

    public function index()
    {

        // Pack512: non-superadmin bypasses selector safely.
        if (function_exists('ec_scope_role') && ec_scope_role() !== 'super_admin') {
            if (function_exists('ec_scope_auto_select_conference')) {
                // ec_scope_auto_select_conference(true);
            }
            $landing = function_exists('ec_scope_landing_url') ? ec_scope_landing_url() : '/easychair/admin/dashboard';
            header("Location: " . $landing);
            exit;
        }

$this->requireAccess();
        $conference = $this->conference();

        $q = trim((string)($_GET['q'] ?? ''));

        $where = "WHERE n.conference_id=? AND n.org_id=?";
        $params = [(int)$conference['id'], (int)$conference['org_id']];

        if ($q !== '') {
            $where .= " AND (u.email LIKE ? OR n.title LIKE ? OR n.event_key LIKE ? OR s.submission_no LIKE ?)";
            $like = '%' . $q . '%';
            array_push($params, $like, $like, $like, $like);
        }

        $stmt = $this->db()->prepare("
            SELECT n.*, u.email, CONCAT(COALESCE(u.first_name,''),' ',COALESCE(u.last_name,'')) AS user_name,
                   s.submission_no, COALESCE(s.title,s.title_en,s.title_ar) AS submission_title
            FROM user_notifications n
            LEFT JOIN users u ON u.id=n.user_id
            LEFT JOIN submissions s ON s.id=n.submission_id
            {$where}
            ORDER BY n.id DESC
            LIMIT 500
        ");
        $stmt->execute($params);
        $notifications = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $stmt = $this->db()->prepare("
            SELECT 
                COUNT(*) AS total,
                SUM(CASE WHEN is_read=0 THEN 1 ELSE 0 END) AS unread,
                SUM(CASE WHEN is_read=1 THEN 1 ELSE 0 END) AS read_count
            FROM user_notifications
            WHERE conference_id=?
              AND org_id=?
        ");
        $stmt->execute([(int)$conference['id'], (int)$conference['org_id']]);
        $stats = $stmt->fetch(\PDO::FETCH_ASSOC) ?: [];

        ob_start();
        require BASE_PATH . '/app/views/admin/notification_audit/index.php';
        $content = ob_get_clean();

        require BASE_PATH . '/app/views/layouts/admin_layout.php';
    }
}
