<?php
namespace App\Controllers;

use App\Core\Database;

class AdminSubmissionSearchController
{
    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 (!in_array($this->role(), ['super_admin','org_admin','admin','organizer','conference_chair','track_chair'], true)) {
            http_response_code(403);
            exit("Access denied.");
        }
    }

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

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

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

        if ($this->role() !== 'super_admin') {
            $where .= " AND s.org_id = ? ";
            $params[] = (int)($_SESSION['org_id'] ?? 0);
        }

        if (!empty($_SESSION['conference_id'])) {
            $where .= " AND s.conference_id = ? ";
            $params[] = (int)$_SESSION['conference_id'];
        }

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

        if ($status !== '') {
            $where .= " AND s.status = ? ";
            $params[] = $status;
        }

        if ($stage !== '') {
            $where .= " AND s.stage = ? ";
            $params[] = $stage;
        }

        $stmt = $this->db()->prepare("
            SELECT 
                s.*,
                COALESCE(s.title,s.title_en,s.title_ar,CONCAT('Submission #',s.id)) AS display_title,
                c.short_name AS conference_short_name,
                o.name AS org_name,
                u.email AS author_email,
                CONCAT(COALESCE(u.first_name,''),' ',COALESCE(u.last_name,'')) AS author_name,
                COUNT(DISTINCT v.id) AS files_count,
                COUNT(DISTINCT ra.id) AS assignments_count
            FROM submissions s
            LEFT JOIN conferences c ON c.id=s.conference_id
            LEFT JOIN organizations o ON o.id=s.org_id
            LEFT JOIN users u ON u.id=s.author_id
            LEFT JOIN submission_versions v 
                   ON v.submission_id=s.id
                  AND v.org_id=s.org_id
                  AND v.conference_id=s.conference_id
            LEFT JOIN review_assignments ra
                   ON ra.submission_id=s.id
                  AND ra.org_id=s.org_id
                  AND ra.conference_id=s.conference_id
            {$where}
            GROUP BY s.id
            ORDER BY s.id DESC
            LIMIT 300
        ");
        $stmt->execute($params);
        $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);

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

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