<?php

namespace App\Controllers;

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

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

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

    private function db()
    {
        return Database::getInstance();
    }

    private function tableColumns(string $table): array
    {
        static $cache = [];

        if (isset($cache[$table])) {
            return $cache[$table];
        }

        try {
            $stmt = $this->db()->query("DESCRIBE `$table`");
            $cols = $stmt->fetchAll(\PDO::FETCH_COLUMN);
            $cache[$table] = array_map('strtolower', $cols ?: []);
        } catch (\Throwable $e) {
            $cache[$table] = [];
        }

        return $cache[$table];
    }

    private function hasColumn(string $table, string $column): bool
    {
        return in_array(strtolower($column), $this->tableColumns($table), true);
    }

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

        $db = $this->db();

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

/*
Use submission context first
*/

$conferenceId =
    (int)(
        $_SESSION['submit_conference_id']
        ?? $_SESSION['conference_id']
        ?? 0
    );

/*
Persist session
*/

if ($conferenceId) {

    $_SESSION['conference_id'] =
        $conferenceId;

}

error_log(
    "AUTHOR DASHBOARD DEBUG: user="
    . $userId
    . " conf="
    . $conferenceId
);

        $select = [
            "s.*",
          //"COALESCE(s.title, s.title_en, s.title_ar, CONCAT('Submission #', s.id)) AS display_title",
          "COALESCE(NULLIF(s.title, ''), s.title_en, s.title_ar,CONCAT('Submission #', s.id)) As display_title",

            "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"
        ];

        $sql = "
            SELECT " . implode(",\n", $select) . "
            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 (
        ? = 0
        OR s.conference_id = ?
        OR s.conference_id IS NULL
      )
            GROUP BY s.id
            ORDER BY s.id DESC
        ";

        $stmt = $db->prepare($sql);

        $stmt->execute([
            $userId,
            $conferenceId,
            $conferenceId
        ]);

        $submissions = $stmt->fetchAll(\PDO::FETCH_ASSOC);

error_log(
    "AUTHOR DASHBOARD RESULTS: "
    . count($submissions)
);

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

        $workflow = [
            'submission' => false,
            'screening' => false,
            'review' => false,
            'revision' => false,
            'decision' => false,
            'production' => false,
            'published' => false
        ];

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

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

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

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

            $stage = strtolower((string)($s['stage'] ?? ''));

            if (isset($workflow[$stage])) {
                $workflow[$stage] = true;
            }

            if ($status === 'under_review') {
                $workflow['review'] = true;
            }

            if ($status === 'revision_required') {
                $workflow['revision'] = true;
            }

            if (in_array($status, ['accepted', 'rejected'], true)) {
                $workflow['decision'] = true;
            }

            if ($status === 'published') {
                $workflow['published'] = true;
            }
        }

        $success = $_SESSION['success'] ?? null;
        $error = $_SESSION['error'] ?? null;

        unset($_SESSION['success'], $_SESSION['error']);

        $conference = null;

        if ($conferenceId > 0) {
            try {
                $stmt = $db->prepare("
                    SELECT *
                    FROM conferences
                    WHERE id = ?
                    LIMIT 1
                ");

                $stmt->execute([$conferenceId]);
                $conference = $stmt->fetch(\PDO::FETCH_ASSOC);
            } catch (\Throwable $e) {
                $conference = null;
            }
        }

        ob_start();

        require BASE_PATH . '/app/views/author/dashboard.php';

        $content = ob_get_clean();

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