<?php
declare(strict_types=1);

namespace App\Controllers;

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

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

final class AdminCustomFieldsController extends Controller
{
    private function ensureTable($db): void
    {
        $st = $db->query("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='custom_fields'");
        if ((int)$st->fetchColumn() <= 0) {
            throw new \RuntimeException("custom_fields table missing");
        }
    }

    private function scopes(): array
    {
        return ['registration','submission','review'];
    }

    private function types(): array
    {
        return ['text','textarea','email','number','date','select','checkbox','radio'];
    }

    public function index(): void
    {
        require_admin_area();
        $db = Database::getInstance();
        $this->ensureTable($db);

        $scope = trim((string)($_GET['scope'] ?? 'registration'));
        if (!in_array($scope, $this->scopes(), true)) $scope = 'registration';

        $st = $db->prepare("SELECT * FROM custom_fields WHERE scope=:s ORDER BY sort_order ASC, id ASC");
        $st->execute([':s'=>$scope]);
        $rows = $st->fetchAll() ?: [];

        $edit = null;
        $eid = (int)($_GET['edit'] ?? 0);
        if ($eid > 0) {
            $st = $db->prepare("SELECT * FROM custom_fields WHERE id=:id LIMIT 1");
            $st->execute([':id'=>$eid]);
            $edit = $st->fetch() ?: null;
        }

        $this->view('admin/custom_fields/index', compact('rows','scope','edit'));
    }

    public function save(): void
    {
        require_admin_area();
        $db = Database::getInstance();
        $this->ensureTable($db);

        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { http_response_code(405); return; }

        $id = (int)($_POST['id'] ?? 0);
        $scope = trim((string)($_POST['scope'] ?? 'registration'));
        if (!in_array($scope, $this->scopes(), true)) $scope = 'registration';

        $key = trim((string)($_POST['field_key'] ?? ''));
        $label_en = trim((string)($_POST['label_en'] ?? ''));
        $label_ar = trim((string)($_POST['label_ar'] ?? ''));
        $type = trim((string)($_POST['field_type'] ?? 'text'));
        if (!in_array($type, $this->types(), true)) $type = 'text';

        $opts = trim((string)($_POST['field_options'] ?? ''));
        $ph_en = trim((string)($_POST['placeholder_en'] ?? ''));
        $ph_ar = trim((string)($_POST['placeholder_ar'] ?? ''));
        $help_en = trim((string)($_POST['help_text_en'] ?? ''));
        $help_ar = trim((string)($_POST['help_text_ar'] ?? ''));
        $req = (int)($_POST['is_required'] ?? 0);
        $act = (int)($_POST['is_active'] ?? 1);
        $sort = (int)($_POST['sort_order'] ?? 0);

        if ($key === '' || $label_en === '' || $label_ar === '') {
            if (function_exists('flash_set')) flash_set('danger', 'Missing key/labels');
            header('Location: '.base_path('admin/custom-fields?scope='.$scope));
            exit;
        }

        $key = preg_replace('/\s+/', '_', $key) ?? $key;

        // For select/radio: store as JSON array if possible; otherwise store newline list as-is
        if (in_array($type, ['select','radio'], true)) {
            if ($opts !== '') {
                $decoded = json_decode($opts, true);
                if (is_array($decoded)) {
                    $opts = json_encode(array_values($decoded), JSON_UNESCAPED_UNICODE);
                }
            }
        } else {
            // other types do not need options
            $opts = '';
        }

        if ($id > 0) {
            $db->prepare("
              UPDATE custom_fields
              SET scope=:s,
                  module_name=:m,
                  field_key=:k,
                  label_en=:le,
                  label_ar=:la,
                  field_type=:t,
                  field_options=:o,
                  placeholder_en=:pe,
                  placeholder_ar=:pa,
                  help_text_en=:he,
                  help_text_ar=:ha,
                  is_required=:r,
                  is_active=:a,
                  sort_order=:so
              WHERE id=:id
            ")->execute([
              ':s'=>$scope,
              ':m'=>$scope,
              ':k'=>$key,
              ':le'=>$label_en,
              ':la'=>$label_ar,
              ':t'=>$type,
              ':o'=>($opts!==''?$opts:null),
              ':pe'=>($ph_en!==''?$ph_en:null),
              ':pa'=>($ph_ar!==''?$ph_ar:null),
              ':he'=>($help_en!==''?$help_en:null),
              ':ha'=>($help_ar!==''?$help_ar:null),
              ':r'=>$req?1:0,
              ':a'=>$act?1:0,
              ':so'=>$sort,
              ':id'=>$id
            ]);
            if (function_exists('flash_set')) flash_set('success', 'Custom field updated');
        } else {
            $db->prepare("
              INSERT INTO custom_fields(
                scope, module_name,
                field_key, label_en, label_ar,
                field_type, field_options,
                placeholder_en, placeholder_ar,
                help_text_en, help_text_ar,
                is_required, is_active, sort_order
              ) VALUES(
                :s,:m,:k,:le,:la,:t,:o,:pe,:pa,:he,:ha,:r,:a,:so
              )
            ")->execute([
              ':s'=>$scope,
              ':m'=>$scope,
              ':k'=>$key,
              ':le'=>$label_en,
              ':la'=>$label_ar,
              ':t'=>$type,
              ':o'=>($opts!==''?$opts:null),
              ':pe'=>($ph_en!==''?$ph_en:null),
              ':pa'=>($ph_ar!==''?$ph_ar:null),
              ':he'=>($help_en!==''?$help_en:null),
              ':ha'=>($help_ar!==''?$help_ar:null),
              ':r'=>$req?1:0,
              ':a'=>$act?1:0,
              ':so'=>$sort
            ]);
            if (function_exists('flash_set')) flash_set('success', 'Custom field added');
        }

        header('Location: '.base_path('admin/custom-fields?scope='.$scope));
        exit;
    }

    public function toggle(): void
    {
        require_admin_area();
        $db = Database::getInstance();
        $this->ensureTable($db);

        $id = (int)($_GET['id'] ?? 0);
        $scope = trim((string)($_GET['scope'] ?? 'registration'));
        if ($id > 0) {
            $db->prepare("UPDATE custom_fields SET is_active=IF(is_active=1,0,1) WHERE id=:id")->execute([':id'=>$id]);
            if (function_exists('flash_set')) flash_set('success', 'Toggled');
        }
        header('Location: '.base_path('admin/custom-fields?scope='.$scope));
        exit;
    }

    public function delete(): void
    {
        require_admin_area();
        $db = Database::getInstance();
        $this->ensureTable($db);

        $id = (int)($_GET['id'] ?? 0);
        $scope = trim((string)($_GET['scope'] ?? 'registration'));
        if ($id > 0) {
            $db->prepare("DELETE FROM custom_fields WHERE id=:id")->execute([':id'=>$id]);
            if (function_exists('flash_set')) flash_set('success', 'Deleted');
        }
        header('Location: '.base_path('admin/custom-fields?scope='.$scope));
        exit;
    }
}
