<?php
namespace App\Controllers;

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

use App\Core\Database;

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

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

    private function role(): string
    {
        return (string)($_SESSION['conference_role'] ?? $_SESSION['role'] ?? $_SESSION['user_role'] ?? '');
    }

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

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

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

        if (!in_array($this->role(), ['super_admin','org_admin','admin','conference_chair'], true)) {
            http_response_code(403);
            exit("Access denied.");
        }
    }

    private function conference(): array
    {
        $stmt = $this->db()->prepare("SELECT * FROM conferences WHERE id=? LIMIT 1");
        $stmt->execute([(int)$_SESSION['conference_id']]);
        $c = $stmt->fetch(\PDO::FETCH_ASSOC);

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

        if ($this->role() !== 'super_admin' && (int)$c['org_id'] !== (int)($_SESSION['org_id'] ?? 0)) {
            http_response_code(403);
            exit("Invalid organization access.");
        }

        return $c;
    }

    public function index()
    {

        // Pack512: non-superadmin bypasses selector safely.
        if (function_exists('ec_scope_role') && ec_scope_role() !== 'super_admin') {
            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->requireAccess();
        $conference = $this->conference();

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

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

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

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

    public function saveRules()
    {
        $this->requireAccess();
        $conference = $this->conference();

        $rules = $_POST['rules'] ?? [];

        foreach ($rules as $id => $r) {
            $stmt = $this->db()->prepare("
                UPDATE profile_field_rules
                SET is_required=?,
                    is_visible=?,
                    sort_order=?,
                    help_text=?,
                    updated_at=NOW()
                WHERE id=?
                  AND conference_id=?
                  AND org_id=?
            ");
            $stmt->execute([
                !empty($r['is_required']) ? 1 : 0,
                !empty($r['is_visible']) ? 1 : 0,
                (int)($r['sort_order'] ?? 100),
                trim((string)($r['help_text'] ?? '')),
                (int)$id,
                (int)$conference['id'],
                (int)$conference['org_id']
            ]);
        }

        $_SESSION['flash_success'] = 'Profile field rules saved.';
        header("Location: /easychair/admin/profile-fields?saved=1");
        exit;
    }

    private function normalizeKey(string $key): string
    {
        $key = strtolower(trim($key));
        $key = preg_replace('/[^a-z0-9_]+/', '_', $key);
        $key = trim($key, '_');

        if ($key === '') {
            $key = 'custom_' . date('YmdHis');
        }

        return substr($key, 0, 120);
    }

    public function storeCustom()
    {
        $this->requireAccess();
        $conference = $this->conference();

        $roleCode = trim((string)($_POST['role_code'] ?? 'all'));
        if ($roleCode === '') {
            $roleCode = 'all';
        }

        $fieldKey = $this->normalizeKey((string)($_POST['field_key'] ?? ''));
        $fieldLabel = trim((string)($_POST['field_label'] ?? ''));
        $fieldType = trim((string)($_POST['field_type'] ?? 'text'));

        if ($fieldLabel === '') {
            $_SESSION['flash_error'] = 'Custom field label is required.';
            header("Location: /easychair/admin/profile-fields");
            exit;
        }

        if (!in_array($fieldType, ['text','textarea','select','number','date','url','email'], true)) {
            $fieldType = 'text';
        }

        $stmt = $this->db()->prepare("
            INSERT INTO profile_custom_fields
            (org_id, conference_id, role_code, field_key, field_label, field_label_ar, field_type,
             options_text, is_required, is_visible, sort_order, help_text, created_by)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                field_label=VALUES(field_label),
                field_label_ar=VALUES(field_label_ar),
                field_type=VALUES(field_type),
                options_text=VALUES(options_text),
                is_required=VALUES(is_required),
                is_visible=VALUES(is_visible),
                sort_order=VALUES(sort_order),
                help_text=VALUES(help_text),
                updated_at=NOW()
        ");
        $stmt->execute([
            (int)$conference['org_id'],
            (int)$conference['id'],
            $roleCode,
            $fieldKey,
            $fieldLabel,
            trim((string)($_POST['field_label_ar'] ?? '')),
            $fieldType,
            trim((string)($_POST['options_text'] ?? '')),
            !empty($_POST['is_required']) ? 1 : 0,
            !empty($_POST['is_visible']) ? 1 : 0,
            (int)($_POST['sort_order'] ?? 500),
            trim((string)($_POST['help_text'] ?? '')),
            (int)$_SESSION['user_id']
        ]);

        $_SESSION['flash_success'] = 'Custom profile field saved.';
        header("Location: /easychair/admin/profile-fields?custom=1");
        exit;
    }

    public function deleteCustom()
    {
        $this->requireAccess();
        $conference = $this->conference();

        $id = (int)($_GET['id'] ?? 0);

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

        $_SESSION['flash_success'] = 'Custom field deleted.';
        header("Location: /easychair/admin/profile-fields?deleted=1");
        exit;
    }

    public function bulkUpdate()
    {
        $this->requireAccess();
        $conference = $this->conference();

        $roleCode = trim((string)($_POST['role_code'] ?? ''));
        $fieldKey = trim((string)($_POST['field_key'] ?? ''));
        $action = trim((string)($_POST['bulk_action'] ?? ''));

        if ($roleCode === '' || $fieldKey === '' || $action === '') {
            $_SESSION['flash_error'] = 'Role, field, and action are required for bulk update.';
            header("Location: /easychair/admin/profile-fields");
            exit;
        }

        $allowed = ['required','optional','visible','hidden'];
        if (!in_array($action, $allowed, true)) {
            $_SESSION['flash_error'] = 'Invalid bulk action.';
            header("Location: /easychair/admin/profile-fields");
            exit;
        }

        $set = '';
        if ($action === 'required') {
            $set = 'is_required=1, is_visible=1';
        } elseif ($action === 'optional') {
            $set = 'is_required=0';
        } elseif ($action === 'visible') {
            $set = 'is_visible=1';
        } elseif ($action === 'hidden') {
            $set = 'is_visible=0, is_required=0';
        }

        $stmt = $this->db()->prepare("
            UPDATE profile_field_rules
            SET {$set},
                updated_at=NOW()
            WHERE conference_id=?
              AND org_id=?
              AND role_code=?
              AND field_key=?
        ");
        $stmt->execute([
            (int)$conference['id'],
            (int)$conference['org_id'],
            $roleCode,
            $fieldKey
        ]);

        $_SESSION['flash_success'] = "Bulk update applied. Rows affected: " . $stmt->rowCount();
        header("Location: /easychair/admin/profile-fields?role=" . urlencode($roleCode));
        exit;
    }


}