<?php
declare(strict_types=1);

namespace App\Controllers;

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

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

final class AdminCustomFieldsTenantController extends Controller
{
    private function guard(): array {
        require_admin_or_chair_tenant();
        require_org_context();
        $db=Database::getInstance();
        $orgId=(int)current_org_id();
        return [$db,$orgId];
    }

    private function tableHasOrg(PDO $db): bool {
        $st=$db->prepare("SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='custom_fields' AND COLUMN_NAME='org_id'");
        $st->execute();
        return (int)$st->fetchColumn() > 0;
    }

    public function index(): void
    {
        [$db,$orgId]=$this->guard();
        $scope=trim((string)($_GET['scope'] ?? 'registration'));
        if(!in_array($scope,['registration','submission','review'],true)) $scope='registration';

        $hasOrg=$this->tableHasOrg($db);

        $sql="SELECT * FROM custom_fields WHERE scope=:s";
        $bind=[':s'=>$scope];
        if($hasOrg){ $sql.=" AND (org_id=:o OR org_id IS NULL)"; $bind[':o']=$orgId; }
        $sql.=" ORDER BY sort_order ASC, id ASC";

        $st=$db->prepare($sql);
        $st->execute($bind);
        $rows=$st->fetchAll(PDO::FETCH_ASSOC)?:[];

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

    public function save(): void
    {
        [$db,$orgId]=$this->guard();
        if(($_SERVER['REQUEST_METHOD']??'GET')!=='POST'){ http_response_code(405); exit; }

        $id=(int)($_POST['id'] ?? 0);
        $scope=trim((string)($_POST['scope'] ?? 'registration'));
        if(!in_array($scope,['registration','submission','review'],true)) $scope='registration';

        $field_key=trim((string)($_POST['field_key'] ?? ''));
        $label_en=trim((string)($_POST['label_en'] ?? ''));
        $label_ar=trim((string)($_POST['label_ar'] ?? ''));
        $field_type=trim((string)($_POST['field_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))?1:0;
        $active=((int)($_POST['is_active'] ?? 1))?1:0;
        $sort=(int)($_POST['sort_order'] ?? 0);

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

        $allowed=['text','textarea','email','number','date','select','checkbox','radio'];
        if(!in_array($field_type,$allowed,true)) $field_type='text';

        $hasOrg=$this->tableHasOrg($db);

        if($id>0){
            $sql="UPDATE custom_fields SET
              scope=:scope,
              module_name=:module_name,
              field_key=:field_key,
              label_en=:label_en, label_ar=:label_ar,
              field_type=:field_type,
              field_options=:field_options,
              placeholder_en=:placeholder_en, placeholder_ar=:placeholder_ar,
              help_text_en=:help_text_en, help_text_ar=:help_text_ar,
              is_required=:is_required, is_active=:is_active, sort_order=:sort_order
              WHERE id=:id";
            $bind=[
              ':scope'=>$scope, ':module_name'=>$scope,
              ':field_key'=>$field_key,
              ':label_en'=>$label_en, ':label_ar'=>$label_ar,
              ':field_type'=>$field_type,
              ':field_options'=>($opts!==''?$opts:null),
              ':placeholder_en'=>($ph_en!==''?$ph_en:null), ':placeholder_ar'=>($ph_ar!==''?$ph_ar:null),
              ':help_text_en'=>($help_en!==''?$help_en:null), ':help_text_ar'=>($help_ar!==''?$help_ar:null),
              ':is_required'=>$req, ':is_active'=>$active, ':sort_order'=>$sort,
              ':id'=>$id
            ];
            if($hasOrg){
                // prevent editing other org rows
                $sql.=" AND (org_id=:o OR org_id IS NULL)";
                $bind[':o']=$orgId;
            }
            $st=$db->prepare($sql);
            $st->execute($bind);
        } else {
            $cols="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";
            $vals=":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";
            $bind=[
              ':scope'=>$scope, ':module_name'=>$scope,
              ':field_key'=>$field_key,
              ':label_en'=>$label_en, ':label_ar'=>$label_ar,
              ':field_type'=>$field_type,
              ':field_options'=>($opts!==''?$opts:null),
              ':placeholder_en'=>($ph_en!==''?$ph_en:null), ':placeholder_ar'=>($ph_ar!==''?$ph_ar:null),
              ':help_text_en'=>($help_en!==''?$help_en:null), ':help_text_ar'=>($help_ar!==''?$help_ar:null),
              ':is_required'=>$req, ':is_active'=>$active, ':sort_order'=>$sort,
            ];
            if($hasOrg){
                $cols="org_id,".$cols;
                $vals=":org_id,".$vals;
                $bind[':org_id']=$orgId;
            }
            $st=$db->prepare("INSERT INTO custom_fields($cols) VALUES($vals)");
            $st->execute($bind);
        }

        if(function_exists('flash_set')) flash_set('success','Saved');
        header('Location: '.base_path('admin/custom-fields?scope='.$scope)); exit;
    }

    public function toggle(): void
    {
        [$db,$orgId]=$this->guard();
        if(($_SERVER['REQUEST_METHOD']??'GET')!=='POST'){ http_response_code(405); exit; }

        $id=(int)($_POST['id'] ?? 0);
        $scope=trim((string)($_POST['scope'] ?? 'registration'));
        if(!in_array($scope,['registration','submission','review'],true)) $scope='registration';

        $hasOrg=$this->tableHasOrg($db);

        $sql="UPDATE custom_fields SET is_active=IF(is_active=1,0,1) WHERE id=:id";
        $bind=[':id'=>$id];
        if($hasOrg){ $sql.=" AND (org_id=:o OR org_id IS NULL)"; $bind[':o']=$orgId; }
        $db->prepare($sql)->execute($bind);

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

    public function delete(): void
    {
        [$db,$orgId]=$this->guard();
        if(($_SERVER['REQUEST_METHOD']??'GET')!=='POST'){ http_response_code(405); exit; }

        $id=(int)($_POST['id'] ?? 0);
        $scope=trim((string)($_POST['scope'] ?? 'registration'));
        if(!in_array($scope,['registration','submission','review'],true)) $scope='registration';

        $hasOrg=$this->tableHasOrg($db);

        $sql="DELETE FROM custom_fields WHERE id=:id";
        $bind=[':id'=>$id];
        if($hasOrg){ $sql.=" AND (org_id=:o OR org_id IS NULL)"; $bind[':o']=$orgId; }
        $db->prepare($sql)->execute($bind);

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