<?php
namespace App\Core;

use App\Core\Database;

class ProfileGuard
{
    private \PDO $db;

    public function __construct()
    {
        $this->db = Database::getInstance();
    }

    public function getProfile(int $userId, int $conferenceId): ?array
    {
        $stmt = $this->db->prepare("
            SELECT *
            FROM user_profiles
            WHERE user_id=?
              AND conference_id=?
            LIMIT 1
        ");
        $stmt->execute([$userId, $conferenceId]);
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);

        return $row ?: null;
    }

    public function userRoleCode(int $userId, int $conferenceId): string
    {
        $stmt = $this->db->prepare("
            SELECT r.code
            FROM user_conferences uc
            JOIN roles r ON r.id=uc.role_id
            WHERE uc.user_id=?
              AND uc.conference_id=?
            LIMIT 1
        ");
        $stmt->execute([$userId, $conferenceId]);
        return (string)($stmt->fetchColumn() ?: '');
    }

    public function requiredRules(int $conferenceId, string $roleCode): array
    {
        $stmt = $this->db->prepare("
            SELECT *
            FROM profile_field_rules
            WHERE conference_id=?
              AND role_code=?
              AND is_visible=1
              AND is_required=1
            ORDER BY sort_order, field_label
        ");
        $stmt->execute([$conferenceId, $roleCode]);
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    public function requiredCustomFields(int $conferenceId, string $roleCode): array
    {
        $stmt = $this->db->prepare("
            SELECT *
            FROM profile_custom_fields
            WHERE conference_id=?
              AND is_visible=1
              AND is_required=1
              AND role_code IN ('all', ?)
            ORDER BY sort_order, field_label
        ");
        $stmt->execute([$conferenceId, $roleCode]);
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    public function missingFields(int $userId, int $conferenceId): array
    {
        $profile = $this->getProfile($userId, $conferenceId);
        $roleCode = $this->userRoleCode($userId, $conferenceId);

        if (!$roleCode) {
            $roleCode = (string)($_SESSION['conference_role'] ?? $_SESSION['role'] ?? 'author');
        }

        $missing = [];

        foreach ($this->requiredRules($conferenceId, $roleCode) as $rule) {
            $key = (string)$rule['field_key'];

            if (!$profile || trim((string)($profile[$key] ?? '')) === '') {
                $missing[] = (string)($rule['field_label'] ?: $key);
            }
        }

        foreach ($this->requiredCustomFields($conferenceId, $roleCode) as $field) {
            $stmt = $this->db->prepare("
                SELECT field_value
                FROM profile_custom_values
                WHERE user_id=?
                  AND conference_id=?
                  AND custom_field_id=?
                LIMIT 1
            ");
            $stmt->execute([$userId, $conferenceId, (int)$field['id']]);
            $value = trim((string)$stmt->fetchColumn());

            if ($value === '') {
                $missing[] = (string)($field['field_label'] ?: $field['field_key']);
            }
        }

        return $missing;
    }

    public function isComplete(int $userId, int $conferenceId): bool
    {
        return count($this->missingFields($userId, $conferenceId)) === 0;
    }

    public function ensureCompleteOrRedirect(int $userId, int $conferenceId, string $returnUrl = ''): void
    {
        if ($this->isComplete($userId, $conferenceId)) {
            return;
        }

        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        $_SESSION['profile_guard_message'] = 'Please complete your academic profile before continuing.';
        $_SESSION['profile_guard_missing'] = $this->missingFields($userId, $conferenceId);

        $target = '/easychair/profile';
        if ($returnUrl !== '') {
            $target .= '?return=' . urlencode($returnUrl);
        }

        header("Location: {$target}");
        exit;
    }

    public function refreshCompletion(int $userId, int $conferenceId): void
    {
        $complete = $this->isComplete($userId, $conferenceId) ? 1 : 0;

        $stmt = $this->db->prepare("
            UPDATE user_profiles
            SET is_profile_complete=?
            WHERE user_id=?
              AND conference_id=?
        ");
        $stmt->execute([$complete, $userId, $conferenceId]);
    }
}
