<?php

namespace App\Controllers;

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

class AdminReviewFormController extends Controller
{

private function requireAdmin()
{
    if (!isset($_SESSION['user_id'])) {
        header("Location: /easychair/login");
        exit;
    }

    /*
    Ensure conference context exists
    */

    if (
        empty($_SESSION['conference_id']) ||
        empty($_SESSION['org_id'])
    ) {

        $db =
            \App\Core\Database::getInstance();

        $stmt =
            $db->prepare("
                SELECT
                    id,
                    org_id
                FROM conferences
                ORDER BY id ASC
                LIMIT 1
            ");

        $stmt->execute();

        $conf =
            $stmt->fetch(\PDO::FETCH_ASSOC);

        if ($conf) {

            $_SESSION['conference_id'] =
                (int) $conf['id'];

            $_SESSION['org_id'] =
                (int) $conf['org_id'];

        } else {

            die("No conference configured.");
        }
    }
}

/*
===============================
CREATE FORM
===============================
*/

public function create()
{
    $this->requireAdmin();

    $this->renderAdmin(
        'admin/review_form/create',
        [
            'title' => 'Add Review Criterion'
        ]
    );
}

/*
===============================
LIST CRITERIA
===============================
*/

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

    $db = Database::getInstance();

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

    $stmt = $db->prepare("
        SELECT *
        FROM review_criteria
        WHERE conference_id = ?
        ORDER BY
            sort_order ASC,
            id ASC
    ");

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

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

    error_log(
        'REVIEW CRITERIA PAGE: conf=' .
        $conferenceId .
        ' criteria=' .
        count($criteria)
    );

    $this->renderAdmin(
        'admin/review_form/index',
        [
            'title' => 'Review Form',
            'criteria' => $criteria
        ]
    );
}

/*
===============================
STORE NEW
===============================
*/

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

    $db = Database::getInstance();

    $title_ar =
        trim($_POST['title_ar'] ?? '');

    $title_en =
        trim($_POST['title_en'] ?? '');

    $description_ar =
        trim($_POST['description_ar'] ?? '');

    $description_en =
        trim($_POST['description_en'] ?? '');

    $max_score =
        floatval($_POST['max_score'] ?? 10);

    $weight =
        floatval($_POST['weight'] ?? 1);

    $sort_order =
        intval($_POST['sort_order'] ?? 1);

    if (!$title_ar && !$title_en) {
        die("Criterion title required");
    }

    $criterionKey =
        strtolower(
            preg_replace(
                '/[^a-zA-Z0-9_]+/',
                '_',
                $title_en ?: $title_ar
            )
        );

    $stmt = $db->prepare("
        INSERT INTO review_criteria
        (
            conference_id,
            criterion_key,
            title_ar,
            title_en,
            description_ar,
            description_en,
            max_score,
            weight,
            sort_order,
            is_active,
            created_at
        )
        VALUES
        (
            ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, NOW()
        )
    ");

    $stmt->execute([

        $_SESSION['conference_id'],
        $criterionKey,
        $title_ar,
        $title_en,
        $description_ar,
        $description_en,
        $max_score,
        $weight,
        $sort_order

    ]);

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

    exit;
}

/*
===============================
EDIT
===============================
*/

public function edit()
{
    $this->requireAdmin();

    $db = Database::getInstance();

    $id =
        isset($_GET['id'])
        ? intval($_GET['id'])
        : 0;

    if (!$id) {
        die("Invalid criterion id");
    }

    $stmt =
        $db->prepare("
            SELECT *
            FROM review_criteria
            WHERE id = ?
            AND conference_id = ?
            LIMIT 1
        ");

    $stmt->execute([
        $id,
        $_SESSION['conference_id']
    ]);

    $criterion =
        $stmt->fetch(\PDO::FETCH_ASSOC);

    if (!$criterion) {
        die("Criterion not found");
    }

    $this->renderAdmin(
        'admin/review_form/edit',
        [
            'title' => 'Edit Review Criterion',
            'criterion' => $criterion
        ]
    );
}

/*
===============================
SAVE UPDATE
===============================
*/

public function save()
{
    $this->requireAdmin();

    $db = Database::getInstance();

    $id =
        intval($_POST['id']);

    $title_ar =
        trim($_POST['title_ar'] ?? '');

    $title_en =
        trim($_POST['title_en'] ?? '');

    $criterionKey =
        strtolower(
            preg_replace(
                '/[^a-zA-Z0-9_]+/',
                '_',
                $title_en ?: $title_ar
            )
        );

    $stmt =
        $db->prepare("
            UPDATE review_criteria
            SET
                criterion_key = ?,
                title_ar = ?,
                title_en = ?,
                description_ar = ?,
                description_en = ?,
                max_score = ?,
                weight = ?,
                sort_order = ?
            WHERE id = ?
            AND conference_id = ?
        ");

    $stmt->execute([

        $criterionKey,
        $title_ar,
        $title_en,
        trim($_POST['description_ar']),
        trim($_POST['description_en']),
        floatval($_POST['max_score']),
        floatval($_POST['weight']),
        intval($_POST['sort_order']),
        $id,
        $_SESSION['conference_id']

    ]);

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

    exit;
}

/*
===============================
DELETE
===============================
*/

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

    $db = Database::getInstance();

    $id =
        intval($_GET['id']);

    /*
    SAFE DELETE:
    prevent FK failures
    */

    $stmtCheck =
        $db->prepare("
            SELECT COUNT(*) 
            FROM review_criterion_scores
            WHERE criterion_id = ?
        ");

    $stmtCheck->execute([$id]);

    $used =
        (int)$stmtCheck->fetchColumn();

    if ($used > 0) {

        $db->prepare("
            UPDATE review_criteria
            SET is_active = 0
            WHERE id = ?
        ")->execute([$id]);

    } else {

        $db->prepare("
            DELETE
            FROM review_criteria
            WHERE id = ?
            AND conference_id = ?
        ")->execute([
            $id,
            $_SESSION['conference_id']
        ]);
    }

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

    exit;
}

/*
===============================
TOGGLE ACTIVE
===============================
*/

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

    $db = Database::getInstance();

    $id =
        intval($_GET['id']);

    $db->prepare("
        UPDATE review_criteria
        SET is_active =
            CASE
                WHEN is_active = 1 THEN 0
                ELSE 1
            END
        WHERE id = ?
        AND conference_id = ?
    ")->execute([
        $id,
        $_SESSION['conference_id']
    ]);

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

    exit;
}

private function renderAdmin($view, $data = [])
{
    extract($data);

    ob_start();

    require BASE_PATH . "/app/views/$view.php";

    $content = ob_get_clean();

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

/*
===============================
IMPORT DEFAULT
===============================
*/

public function importDefault()
{
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }

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

    $db = \App\Core\Database::getInstance();

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

    if (!$conferenceId) {
        exit('Conference missing.');
    }

    /*
    RESET CURRENT CONFERENCE
    */

    $db->prepare("
        DELETE FROM review_criteria
        WHERE conference_id = ?
    ")->execute([
        $conferenceId
    ]);

    /*
    IMPORT DEFAULT FROM CONF 1
    */

    $stmt = $db->prepare("
        INSERT INTO review_criteria
        (
            conference_id,
            criterion_key,
            title_ar,
            title_en,
            description_ar,
            description_en,
            max_score,
            weight,
            sort_order,
            is_active,
            created_at
        )

        SELECT
            ?,
            criterion_key,
            title_ar,
            title_en,
            description_ar,
            description_en,
            max_score,
            weight,
            sort_order,
            is_active,
            NOW()

        FROM review_criteria

        WHERE conference_id = 1

        ORDER BY id ASC
    ");

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

    error_log(
        'REVIEW CRITERIA IMPORTED: conf=' .
        $conferenceId
    );

    header(
        "Location: /easychair/admin/review-form?import=success"
    );

    exit;
}

}
