<?php
namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/permissions.php';

require_once BASE_PATH . '/app/helpers/conference_scope.php';

use App\Core\Controller;
use App\Core\Database;
use App\Middleware\RoleGuard;

class AdminSubmissionsController extends Controller
{
    public function index(): void
    {
        RoleGuard::allow(['superadmin']);

        $db = Database::getInstance();

        $submissions = $db->query("
            SELECT s.id,
                   COALESCE(s.title_en, s.title_ar) AS title,
                   s.status,
                   COALESCE(c.title_en, c.title_ar) AS conference
            FROM submissions s
            LEFT JOIN conferences c ON s.conference_id=c.id
            ORDER BY s.id DESC
        ")->fetchAll();

        ob_start();

/*
|--------------------------------------------------------------------------
| LOAD REVIEWERS
|--------------------------------------------------------------------------
*/

$reviewers = [];

try {

    $stmtReviewers = $db->query("
        SELECT
            id,
            first_name,
            last_name,
            email
        FROM users
        WHERE role_id = 4
        AND is_active = 1
        ORDER BY first_name ASC,
                 last_name ASC
    ");

    $reviewers =
        $stmtReviewers->fetchAll(PDO::FETCH_ASSOC);

} catch (\Throwable $e) {

    error_log(
        'ADMIN SUBMISSIONS REVIEWERS ERROR: '
        . $e->getMessage()
    );

    $reviewers = [];
}
        require BASE_PATH.'/app/views/admin/submissions/index.php';
        $content = ob_get_clean();

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

    }

public function assignReviewer()
{
    if (!isset($_SESSION['user_id'])) {

        header("Location: /easychair/login");
        exit;

    }

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

    $submissionId =
        (int)($_POST['submission_id'] ?? 0);

    $reviewerIds =
        $_POST['reviewer_ids'] ?? [];

    if (!$submissionId) {

        die("Submission ID missing.");

    }

    foreach ($reviewerIds as $reviewerId) {

        $stmt =
            $db->prepare("
                INSERT IGNORE INTO
                submission_reviewers
                (
                    submission_id,
                    reviewer_id,
                    assigned_at
                )
                VALUES
                (?, ?, NOW())
            ");

        $stmt->execute([

            $submissionId,
            (int)$reviewerId

        ]);

    }

    error_log(
        "REVIEWERS ASSIGNED: submission="
        . $submissionId
    );

    header(
        "Location: /easychair/admin/submissions"
    );

    exit;
}





}
