<?php
namespace App\Controllers;

use App\Core\Database;
use App\Core\RoleMatrix;

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

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

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

        if (!RoleMatrix::can('manage_review_form')) {
            http_response_code(403);
            exit("Access denied.");
        }

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

    private function assertConference(): array
    {
        $db = Database::getInstance();

        $cid = (int)$_SESSION['conference_id'];
        $orgId = (int)($_SESSION['org_id'] ?? 0);
        $role = $_SESSION['role'] ?? '';

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

        if (!$conference) {
            exit("Conference not found.");
        }

        if ($role !== 'super_admin' && (int)$conference['org_id'] !== $orgId) {
            http_response_code(403);
            exit("Invalid conference access.");
        }

        return $conference;
    }

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

        $db = Database::getInstance();
        $conference = $this->assertConference();

        $stmt = $db->prepare("
            SELECT *
            FROM review_form_criteria
            WHERE conference_id = ?
              AND org_id = ?
            ORDER BY sort_order ASC, id ASC
        ");
        $stmt->execute([(int)$conference['id'], (int)$conference['org_id']]);
        $criteria = $stmt->fetchAll(\PDO::FETCH_ASSOC);

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

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

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

        $db = Database::getInstance();
        $conference = $this->assertConference();

        $stmt = $db->prepare("
            INSERT INTO review_form_criteria
            (org_id, conference_id, label_ar, label_en, description_ar, description_en, max_score, weight, sort_order, is_active)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
        ");

        $stmt->execute([
            (int)$conference['org_id'],
            (int)$conference['id'],
            trim($_POST['label_ar'] ?? ''),
            trim($_POST['label_en'] ?? ''),
            trim($_POST['description_ar'] ?? ''),
            trim($_POST['description_en'] ?? ''),
            (float)($_POST['max_score'] ?? 10),
            (float)($_POST['weight'] ?? 1),
            (int)($_POST['sort_order'] ?? 1),
        ]);

        header("Location: /easychair/admin/review-form");
        exit;
    }

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

        $db = Database::getInstance();
        $conference = $this->assertConference();
        $id = (int)($_GET['id'] ?? 0);

        $stmt = $db->prepare("
            UPDATE review_form_criteria
            SET is_active = IF(is_active=1,0,1)
            WHERE id = ?
              AND conference_id = ?
              AND org_id = ?
        ");
        $stmt->execute([$id, (int)$conference['id'], (int)$conference['org_id']]);

        header("Location: /easychair/admin/review-form");
        exit;
    }

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

        $db = Database::getInstance();
        $conference = $this->assertConference();
        $id = (int)($_GET['id'] ?? 0);

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

        header("Location: /easychair/admin/review-form");
        exit;
    }
}
