<?php
namespace App\Controllers;

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

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

use App\Core\Database;

class AdminIssueController
{
    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(), ['superadmin','org_admin','admin','organizer','conference_chair','track_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 (!ec_is_superadmin() && (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() !== 'superadmin') {
            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 i.*, COALESCE(ac.articles_count,0) AS articles_count
            FROM proceedings_issues i
            LEFT JOIN (
                SELECT issue_id, COUNT(*) AS articles_count
                FROM proceedings_issue_articles
                GROUP BY issue_id
            ) ac ON ac.issue_id=i.id
            WHERE i.conference_id=?
              AND i.org_id=?
            ORDER BY i.id DESC
        ");
        $stmt->execute([(int)$conference['id'], (int)$conference['org_id']]);
        $issues = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $currentIssue = $issues[0] ?? null;

        $stmt = $this->db()->prepare("
            SELECT 
                a.*,
                s.submission_no,
                COALESCE(s.title,s.title_en,s.title_ar) AS submission_title,
                g.file_path AS galley_file,
                g.original_filename AS galley_name,
                g.galley_label_en,
                g.galley_label_ar,
                g.status AS galley_status,
                g.is_public
            FROM proceedings_issue_articles a
            JOIN submissions s ON s.id=a.submission_id
            LEFT JOIN production_galleys g ON g.id=a.galley_id
            WHERE a.conference_id=?
              AND a.org_id=?
            ORDER BY a.article_order ASC, a.id ASC
        ");
        $stmt->execute([(int)$conference['id'], (int)$conference['org_id']]);
        $articles = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $stmt = $this->db()->prepare("
            SELECT 
                s.id,
                s.submission_no,
                COALESCE(s.title,s.title_en,s.title_ar,CONCAT('Submission #',s.id)) AS display_title,
                g.id AS galley_id,
                g.original_filename,
                g.status AS galley_status
            FROM submissions s
            LEFT JOIN production_galleys g
                   ON g.id = (
                        SELECT MAX(g2.id)
                        FROM production_galleys g2
                        WHERE g2.submission_id=s.id
                          AND g2.status IN ('approved','published')
                   )
            WHERE s.conference_id=?
              AND s.org_id=?
              AND s.status IN ('accepted','production','galley','assigned_to_issue','published')
            ORDER BY s.id DESC
        ");
        $stmt->execute([(int)$conference['id'], (int)$conference['org_id']]);
        $eligibleSubmissions = $stmt->fetchAll(\PDO::FETCH_ASSOC);

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

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

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

        $stmt = $this->db()->prepare("
            INSERT INTO proceedings_issues
            (org_id, conference_id, volume_no, issue_no, publication_date, publication_year,
             isbn, issn, eissn, doi_prefix, status, title_en, title_ar, intro_en, intro_ar, is_active, created_by)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'draft', ?, ?, ?, ?, 1, ?)
            ON DUPLICATE KEY UPDATE
                org_id=VALUES(org_id),
                volume_no=VALUES(volume_no),
                issue_no=VALUES(issue_no),
                publication_date=VALUES(publication_date),
                publication_year=VALUES(publication_year),
                isbn=VALUES(isbn),
                issn=VALUES(issn),
                eissn=VALUES(eissn),
                doi_prefix=VALUES(doi_prefix),
                title_en=VALUES(title_en),
                title_ar=VALUES(title_ar),
                intro_en=VALUES(intro_en),
                intro_ar=VALUES(intro_ar),
                is_active=1,
                updated_at=NOW()
        ");
        $stmt->execute([
            (int)$conference['org_id'],
            (int)$conference['id'],
            trim($_POST['volume_no'] ?? ''),
            trim($_POST['issue_no'] ?? ''),
            $_POST['publication_date'] ?: null,
            trim($_POST['publication_year'] ?? date('Y')),
            trim($_POST['isbn'] ?? ''),
            trim($_POST['issn'] ?? ''),
            trim($_POST['eissn'] ?? ''),
            trim($_POST['doi_prefix'] ?? ''),
            trim($_POST['title_en'] ?? ''),
            trim($_POST['title_ar'] ?? ''),
            trim($_POST['intro_en'] ?? ''),
            trim($_POST['intro_ar'] ?? ''),
            (int)$_SESSION['user_id']
        ]);

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

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

        $issueId = (int)($_POST['issue_id'] ?? 0);
        $submissionId = (int)($_POST['submission_id'] ?? 0);
        $doi = trim($_POST['doi'] ?? '');

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

        if (!$issue) {
            exit("Proceedings issue not found.");
        }

        $stmt = $this->db()->prepare("
            SELECT id
            FROM production_galleys
            WHERE submission_id=?
              AND conference_id=?
              AND org_id=?
              AND status IN ('approved','published')
            ORDER BY sort_order ASC, id DESC
            LIMIT 1
        ");
        $stmt->execute([$submissionId, (int)$conference['id'], (int)$conference['org_id']]);
        $galleyId = $stmt->fetchColumn() ?: null;

        $stmt = $this->db()->prepare("
            INSERT INTO proceedings_issue_articles
            (org_id, conference_id, issue_id, submission_id, galley_id, page_from, page_to, article_order, doi)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                galley_id=VALUES(galley_id),
                page_from=VALUES(page_from),
                page_to=VALUES(page_to),
                article_order=VALUES(article_order),
                doi=VALUES(doi)
        ");
        $stmt->execute([
            (int)$conference['org_id'],
            (int)$conference['id'],
            $issueId,
            $submissionId,
            $galleyId,
            trim($_POST['page_from'] ?? ''),
            trim($_POST['page_to'] ?? ''),
            (int)($_POST['article_order'] ?? 0),
            $doi
        ]);

        $stmt = $this->db()->prepare("
            UPDATE submissions
            SET status='assigned_to_issue',
                stage='issue',
                issue_id=?,
                doi=COALESCE(NULLIF(?,''),doi),
                updated_at=NOW()
            WHERE id=?
              AND conference_id=?
              AND org_id=?
        ");
        $stmt->execute([$issueId, $doi, $submissionId, (int)$conference['id'], (int)$conference['org_id']]);

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

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

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

        $stmt = $this->db()->prepare("
            UPDATE proceedings_issues
            SET status='published',
                is_active=1,
                publication_date=COALESCE(publication_date, CURDATE()),
                publication_year=COALESCE(NULLIF(publication_year,''), YEAR(CURDATE())),
                updated_at=NOW()
            WHERE id=?
              AND conference_id=?
              AND org_id=?
        ");
        $stmt->execute([$issueId, (int)$conference['id'], (int)$conference['org_id']]);

        $stmt = $this->db()->prepare("
            UPDATE submissions s
            JOIN proceedings_issue_articles a ON a.submission_id=s.id
            SET s.status='published',
                s.stage='published',
                s.published_at=NOW(),
                s.updated_at=NOW()
            WHERE a.issue_id=?
              AND a.conference_id=?
              AND a.org_id=?
        ");
        $stmt->execute([$issueId, (int)$conference['id'], (int)$conference['org_id']]);

        $stmt = $this->db()->prepare("
            UPDATE production_galleys g
            JOIN proceedings_issue_articles a ON a.galley_id=g.id
            SET g.status='published',
                g.is_public=1
            WHERE a.issue_id=?
              AND a.conference_id=?
              AND a.org_id=?
        ");
        $stmt->execute([$issueId, (int)$conference['id'], (int)$conference['org_id']]);

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

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

        $stmt = $this->db()->prepare("
            DELETE FROM proceedings_issue_articles
            WHERE id=?
              AND conference_id=?
              AND org_id=?
        ");
        $stmt->execute([(int)($_GET['id'] ?? 0), (int)$conference['id'], (int)$conference['org_id']]);

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