<?php
namespace App\Controllers;

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

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

use App\Core\Database;

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

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

    private function requireReviewer(): 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 (!in_array($role, ['reviewer','track_chair','conference_chair','superadmin','org_admin','admin'], true)) {
            http_response_code(403);
            exit("Reviewer access required.");
        }
    }

    private function assignment(): array
    {
        $assignmentId = (int)($_GET['assignment_id'] ?? $_POST['assignment_id'] ?? 0);

        $stmt = $this->db()->prepare("
            SELECT ra.*, s.submission_no, COALESCE(s.title,s.title_en,s.title_ar) AS submission_title, s.org_id, s.conference_id
            FROM review_assignments ra
            JOIN submissions s ON s.id=ra.submission_id
            WHERE ra.id=?
            LIMIT 1
        ");
        $stmt->execute([$assignmentId]);
        $a = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$a) {
            exit("Assignment not found.");
        }

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

        if ($role === 'reviewer' && (int)$a['reviewer_id'] !== (int)$_SESSION['user_id']) {
            http_response_code(403);
            exit("Invalid reviewer assignment.");
        }

        return $a;
    }

    public function index()
    {

        // Pack512: non-superadmin bypasses selector safely.
        if (function_exists('ec_scope_role') && ec_scope_role() !== 'superadmin') {
            if (function_exists('ec_scope_auto_select_conference')) {
                // ec_scope_auto_select_conference(true);
            }
            $landing = function_exists('ec_scope_landing_url') ? ec_scope_landing_url() : '/easychair/admin/dashboard';
            header("Location: " . $landing);
            exit;
        }

$this->requireReviewer();
        $assignment = $this->assignment();

        $stmt = $this->db()->prepare("
            SELECT *
            FROM reviewer_paper_preferences
            WHERE reviewer_id=?
              AND submission_id=?
            LIMIT 1
        ");
        $stmt->execute([(int)$_SESSION['user_id'], (int)$assignment['submission_id']]);
        $preference = $stmt->fetch(\PDO::FETCH_ASSOC);

        $stmt = $this->db()->prepare("
            SELECT d.*, u.email, CONCAT(COALESCE(u.first_name,''),' ',COALESCE(u.last_name,'')) AS actor_name
            FROM review_discussions d
            LEFT JOIN users u ON u.id=d.actor_id
            WHERE d.submission_id=?
              AND d.conference_id=?
              AND d.org_id=?
              AND d.visibility IN ('reviewers_and_chairs','author_visible')
            ORDER BY d.id DESC
        ");
        $stmt->execute([(int)$assignment['submission_id'], (int)$assignment['conference_id'], (int)$assignment['org_id']]);
        $discussions = $stmt->fetchAll(\PDO::FETCH_ASSOC);

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

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

    public function savePreference()
    {
        $this->requireReviewer();
        $assignment = $this->assignment();

        $preference = $_POST['preference'] ?? 'neutral';
        $allowed = ['want_review','can_review','neutral','not_interested','conflict'];

        if (!in_array($preference, $allowed, true)) {
            $preference = 'neutral';
        }

        $stmt = $this->db()->prepare("
            INSERT INTO reviewer_paper_preferences
            (org_id, conference_id, reviewer_id, submission_id, preference, expertise_score, notes)
            VALUES (?, ?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                preference=VALUES(preference),
                expertise_score=VALUES(expertise_score),
                notes=VALUES(notes),
                updated_at=NOW()
        ");
        $stmt->execute([
            (int)$assignment['org_id'],
            (int)$assignment['conference_id'],
            (int)$_SESSION['user_id'],
            (int)$assignment['submission_id'],
            $preference,
            !empty($_POST['expertise_score']) ? (int)$_POST['expertise_score'] : null,
            trim($_POST['notes'] ?? '')
        ]);

        if ($preference === 'conflict') {
            $stmt = $this->db()->prepare("
                INSERT INTO submission_conflicts
                (org_id, conference_id, submission_id, reviewer_id, conflict_type, reason, declared_by)
                VALUES (?, ?, ?, ?, 'reviewer_declared', ?, ?)
                ON DUPLICATE KEY UPDATE
                    reason=VALUES(reason),
                    declared_by=VALUES(declared_by)
            ");
            $stmt->execute([
                (int)$assignment['org_id'],
                (int)$assignment['conference_id'],
                (int)$assignment['submission_id'],
                (int)$_SESSION['user_id'],
                trim($_POST['notes'] ?? ''),
                (int)$_SESSION['user_id']
            ]);
        }

        header("Location: /easychair/reviewer/interaction?assignment_id=" . (int)$assignment['id']);
        exit;
    }

    public function postDiscussion()
    {
        $this->requireReviewer();
        $assignment = $this->assignment();

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

        if ($message === '') {
            header("Location: /easychair/reviewer/interaction?assignment_id=" . (int)$assignment['id']);
            exit;
        }

        $stmt = $this->db()->prepare("
            INSERT INTO review_discussions
            (org_id, conference_id, submission_id, assignment_id, actor_id, actor_role, visibility, message)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            (int)$assignment['org_id'],
            (int)$assignment['conference_id'],
            (int)$assignment['submission_id'],
            (int)$assignment['id'],
            (int)$_SESSION['user_id'],
            $_SESSION['conference_role'] ?? $_SESSION['role'] ?? '',
            $_POST['visibility'] ?? 'reviewers_and_chairs',
            $message
        ]);

        header("Location: /easychair/reviewer/interaction?assignment_id=" . (int)$assignment['id']);
        exit;
    }
}
