<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;

class AuthorDashboardController extends Controller
{
    private function requireConference(): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

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

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

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

        $db = Database::getInstance();

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

        $stmt = $db->prepare("
            SELECT *
            FROM conferences
            WHERE id = ?
            LIMIT 1
        ");
        $stmt->execute([$conferenceId]);
        $conference = $stmt->fetch(\PDO::FETCH_ASSOC);

        $stmt = $db->prepare("
            SELECT
                s.id,
                s.conference_id,
                s.org_id,
                s.author_id,
                s.submission_no,
                COALESCE(s.title, s.title_en, s.title_ar, CONCAT('Submission #', s.id)) AS display_title,
                s.title,
                s.title_ar,
                s.title_en,
                s.abstract,
                s.abstract_ar,
                s.abstract_en,
                s.keywords,
                s.keywords_ar,
                s.file_path,
                s.original_filename,
                s.response_letter_path,
                s.revision_file,
                s.revision_open_until,
                s.status,
                s.stage,
                s.decision,
                s.recommended_decision,
                s.avg_score,
                s.current_round_no,
                s.current_version,
                s.submitted_at,
                s.created_at,
                s.updated_at,
                COUNT(DISTINCT ra.id) AS assignments_count,
                COUNT(DISTINCT rv.id) AS reviews_count,
                ROUND(AVG(COALESCE(rv.overall_score, rv.score)), 2) AS reviews_avg_score
            FROM submissions s
            LEFT JOIN review_assignments ra ON ra.submission_id = s.id
            LEFT JOIN reviews rv ON rv.submission_id = s.id
            WHERE s.author_id = ?
              AND s.conference_id = ?
            GROUP BY s.id
            ORDER BY s.id DESC
        ");

        $stmt->execute([$userId, $conferenceId]);
        $submissions = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $stats = [
            'total' => 0,
            'draft' => 0,
            'submitted' => 0,
            'under_review' => 0,
            'revision_required' => 0,
            'accepted' => 0,
            'rejected' => 0,
            'published' => 0,
        ];

        foreach ($submissions as $s) {
            $stats['total']++;

            $status = (string)($s['status'] ?? '');

            if (isset($stats[$status])) {
                $stats[$status]++;
            }

            if (in_array($status, ['screening', 'submitted'], true)) {
                $stats['submitted']++;
            }
        }

        $workflow = [];
        try {
            $stmt = $db->prepare("
                SELECT stage, is_enabled
                FROM conference_workflow
                WHERE conference_id = ?
                ORDER BY FIELD(stage,'submission','screening','review','revision','decision','galley','production','issue','published'), id
            ");
            $stmt->execute([$conferenceId]);
            $workflow = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        } catch (\Throwable $e) {
            $workflow = [];
        }

        ob_start();
        require BASE_PATH . '/app/views/author/dashboard.php';
        $content = ob_get_clean();

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