<?php
namespace App\Controllers;

use App\Core\Database;

class AuthorMySubmissionsController
{
    protected function db()
    {
        return Database::getInstance();
    }

    private function startSession(): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }
    }

    private function requireAuthor(): void
    {
        $this->startSession();

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

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

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

        if ($role !== 'author') {
            http_response_code(403);
            exit("Author access required.");
        }
    }

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

        $stmt = $this->db()->prepare("
            SELECT 
                s.*,
                COALESCE(s.title,s.title_en,s.title_ar,CONCAT('Submission #',s.id)) AS display_title,
                COUNT(DISTINCT v.id) AS files_count,
                COUNT(DISTINCT l.id) AS activity_count
            FROM submissions s
            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 submission_activity_log l
                   ON l.submission_id=s.id
                  AND l.org_id=s.org_id
                  AND l.conference_id=s.conference_id
            WHERE s.author_id=?
              AND s.conference_id=?
              AND s.org_id=?
            GROUP BY s.id
            ORDER BY s.id DESC
        ");
        $stmt->execute([
            (int)$_SESSION['user_id'],
            (int)$_SESSION['conference_id'],
            (int)$_SESSION['org_id']
        ]);
        $submissions = $stmt->fetchAll(\PDO::FETCH_ASSOC);

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

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