<?php
namespace App\Controllers;

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

use App\Core\Database;

class AdminNotificationDigestController
{
    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();

        $stmt = $this->db()->prepare("
            SELECT 
                l.*,
                u.email,
                CONCAT(COALESCE(u.first_name,''),' ',COALESCE(u.last_name,'')) AS user_name
            FROM notification_digest_log l
            LEFT JOIN users u ON u.id=l.user_id
            WHERE l.conference_id=?
              AND l.org_id=?
            ORDER BY l.id DESC
            LIMIT 300
        ");
        $stmt->execute([(int)$conference['id'], (int)$conference['org_id']]);
        $logs = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $stmt = $this->db()->prepare("
            SELECT status, COUNT(*) AS total
            FROM notification_digest_log
            WHERE conference_id=?
              AND org_id=?
            GROUP BY status
        ");
        $stmt->execute([(int)$conference['id'], (int)$conference['org_id']]);
        $stats = $stmt->fetchAll(\PDO::FETCH_KEY_PAIR);

        $stmt = $this->db()->prepare("
            SELECT p.notification_type, p.digest_frequency, COUNT(*) AS users_count
            FROM user_notification_preferences p
            WHERE p.conference_id=?
              AND p.org_id=?
              AND p.digest_enabled=1
            GROUP BY p.notification_type, p.digest_frequency
            ORDER BY p.notification_type, p.digest_frequency
        ");
        $stmt->execute([(int)$conference['id'], (int)$conference['org_id']]);
        $enabledPrefs = $stmt->fetchAll(\PDO::FETCH_ASSOC);

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

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

    public function preview()
    {
        $this->requireAccess();
        $conference = $this->conference();

        $stmt = $this->db()->prepare("
            SELECT *
            FROM notification_digest_log
            WHERE id=?
              AND conference_id=?
              AND org_id=?
            LIMIT 1
        ");
        $stmt->execute([
            (int)($_GET['id'] ?? 0),
            (int)$conference['id'],
            (int)$conference['org_id']
        ]);
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$row) {
            exit("Digest log not found.");
        }

        header('Content-Type: text/plain; charset=UTF-8');
        echo "To: " . ($row['recipient_email'] ?? '') . "\n";
        echo "Subject: " . ($row['subject'] ?? '') . "\n";
        echo "Status: " . ($row['status'] ?? '') . "\n";
        echo "Sent: " . ($row['sent_at'] ?? '') . "\n";
        echo "\n---------------- BODY ----------------\n\n";
        echo (string)($row['body'] ?? '');
        echo "\n\n---------------- ERROR ----------------\n\n";
        echo (string)($row['error_message'] ?? '');
        exit;
    }
}
