<?php
namespace App\Controllers;

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

use App\Core\Database;

class AdminNotificationController
{
    private function requireAccess(): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

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

        $role = $_SESSION['role'] ?? $_SESSION['user_role'] ?? '';

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

    public function index()
    {
$this->requireAccess();

        $db = Database::getInstance();

        $role = $_SESSION['role'] ?? '';
        $orgId = (int)($_SESSION['org_id'] ?? 0);
        $conferenceId = (int)($_SESSION['conference_id'] ?? 0);

        $where = " WHERE 1=1 ";
        $params = [];

        if ($role !== 'super_admin') {
            $where .= " AND mo.org_id = ? ";
            $params[] = $orgId;

            if ($conferenceId > 0) {
                $where .= " AND mo.conference_id = ? ";
                $params[] = $conferenceId;
            }
        } elseif ($conferenceId > 0) {
            $where .= " AND mo.conference_id = ? ";
            $params[] = $conferenceId;
        }

        $stmt = $db->prepare("
            SELECT
                mo.*,
                c.short_name,
                s.submission_no
            FROM conference_mail_outbox mo
            LEFT JOIN conferences c ON c.id = mo.conference_id
            LEFT JOIN submissions s ON s.id = mo.submission_id
            {$where}
            ORDER BY mo.id DESC
            LIMIT 200
        ");
        $stmt->execute($params);
        $messages = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $stats = [
            'queued' => 0,
            'sent' => 0,
            'failed' => 0,
            'cancelled' => 0,
        ];

        foreach ($messages as $m) {
            $st = $m['status'] ?? 'queued';
            if (isset($stats[$st])) {
                $stats[$st]++;
            }
        }

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

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

    public function markSent()
    {
        $this->requireAccess();

        $id = (int)($_GET['id'] ?? 0);

        $db = Database::getInstance();

        $stmt = $db->prepare("
            UPDATE conference_mail_outbox
            SET status = 'sent',
                sent_at = NOW()
            WHERE id = ?
        ");
        $stmt->execute([$id]);

        header("Location: /easychair/admin/notifications");
        exit;
    }

    public function cancel()
    {
        $this->requireAccess();

        $id = (int)($_GET['id'] ?? 0);

        $db = Database::getInstance();

        $stmt = $db->prepare("
            UPDATE conference_mail_outbox
            SET status = 'cancelled'
            WHERE id = ?
        ");
        $stmt->execute([$id]);

        header("Location: /easychair/admin/notifications");
        exit;
    }
}
