<?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 AdminEmailTemplatesTenantController 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 hasOrg(PDO $db): bool {
        $st=$db->prepare("SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='email_templates' AND COLUMN_NAME='org_id'");
        $st->execute();
        return (int)$st->fetchColumn() > 0;
    }

    public function index(): void
    {
        [$db,$orgId]=$this->guard();
        $hasOrg=$this->hasOrg($db);

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

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

        $this->view('admin/email_templates/index', compact('rows','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);
        $key=trim((string)($_POST['template_key'] ?? ''));
        $sub_en=trim((string)($_POST['subject_en'] ?? ''));
        $sub_ar=trim((string)($_POST['subject_ar'] ?? ''));
        $body_en=trim((string)($_POST['body_en'] ?? ''));
        $body_ar=trim((string)($_POST['body_ar'] ?? ''));
        $active=((int)($_POST['is_active'] ?? 1))?1:0;

        if($key==='' || $sub_en==='' || $sub_ar==='' || $body_en==='' || $body_ar===''){
            if(function_exists('flash_set')) flash_set('danger','All fields are required');
            header('Location: '.base_path('admin/email-templates')); exit;
        }

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

        if($id>0){
            $sql="UPDATE email_templates SET template_key=:k, subject_en=:se, subject_ar=:sa, body_en=:be, body_ar=:ba, is_active=:ia WHERE id=:id";
            $bind=[':k'=>$key,':se'=>$sub_en,':sa'=>$sub_ar,':be'=>$body_en,':ba'=>$body_ar,':ia'=>$active,':id'=>$id];
            if($hasOrg){ $sql.=" AND (org_id=:o OR org_id IS NULL)"; $bind[':o']=$orgId; }
            $db->prepare($sql)->execute($bind);
        } else {
            if($hasOrg){
                $db->prepare("INSERT INTO email_templates(org_id,template_key,subject_en,subject_ar,body_en,body_ar,is_active) VALUES(:o,:k,:se,:sa,:be,:ba,:ia)")
                   ->execute([':o'=>$orgId,':k'=>$key,':se'=>$sub_en,':sa'=>$sub_ar,':be'=>$body_en,':ba'=>$body_ar,':ia'=>$active]);
            } else {
                $db->prepare("INSERT INTO email_templates(template_key,subject_en,subject_ar,body_en,body_ar,is_active) VALUES(:k,:se,:sa,:be,:ba,:ia)")
                   ->execute([':k'=>$key,':se'=>$sub_en,':sa'=>$sub_ar,':be'=>$body_en,':ba'=>$body_ar,':ia'=>$active]);
            }
        }

        if(function_exists('flash_set')) flash_set('success','Saved');
        header('Location: '.base_path('admin/email-templates')); 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);

        $hasOrg=$this->hasOrg($db);
        $sql="UPDATE email_templates 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/email-templates')); 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);

        $hasOrg=$this->hasOrg($db);
        $sql="DELETE FROM email_templates 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/email-templates')); exit;
    }
}
