<?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 AdminEmailTemplatesController extends Controller
{
    public function index(): void
    {
        require_login();
        require_admin_area();
        if(!can_admin()){ http_response_code(403); echo "Forbidden"; return; }
        $db=Database::getInstance();
        $rows=$db->query("SELECT * FROM email_templates ORDER BY id DESC")->fetchAll()?:[];
        $this->view('admin/email_templates/index',['rows'=>$rows]);
    }

    public function save(): void
    {
        require_login();
        if(!can_admin()){ http_response_code(403); echo "Forbidden"; return; }
        csrf_check();

        $db=Database::getInstance();
        $key=trim((string)($_POST['template_key']??''));
        $se=trim((string)($_POST['subject_en']??''));
        $sa=trim((string)($_POST['subject_ar']??''));
        $be=(string)($_POST['body_en']??'');
        $ba=(string)($_POST['body_ar']??'');
        $act=(int)($_POST['is_active']??1);

        if($key===''||$se===''||$sa===''||$be===''||$ba===''){ header('Location: '.base_path('admin/email-templates')); exit; }

        $db->prepare("INSERT INTO email_templates(template_key,subject_en,subject_ar,body_en,body_ar,is_active)
                      VALUES(:k,:se,:sa,:be,:ba,:a)
                      ON DUPLICATE KEY UPDATE subject_en=VALUES(subject_en),subject_ar=VALUES(subject_ar),body_en=VALUES(body_en),body_ar=VALUES(body_ar),is_active=VALUES(is_active)")
           ->execute([':k'=>$key,':se'=>$se,':sa'=>$sa,':be'=>$be,':ba'=>$ba,':a'=>$act?1:0]);

        header('Location: '.base_path('admin/email-templates')); exit;
    }

    public function delete(): void
    {
        require_login();
        if(!can_admin()){ http_response_code(403); echo "Forbidden"; return; }
        csrf_check();
        $db=Database::getInstance();
        $id=(int)($_POST['id']??0);
        if($id>0) $db->prepare("DELETE FROM email_templates WHERE id=:id")->execute([':id'=>$id]);
        header('Location: '.base_path('admin/email-templates')); exit;
    }
}
