<?php
namespace App\Controllers;

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

use App\Core\Database;

class AdminConferenceEmailTemplateController
{
    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','organizer','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;
    }

    private function columnExists(string $table, string $column): bool
    {
        $stmt = $this->db()->prepare("
            SELECT COUNT(*)
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_SCHEMA=DATABASE()
              AND TABLE_NAME=?
              AND COLUMN_NAME=?
        ");
        $stmt->execute([$table, $column]);
        return (int)$stmt->fetchColumn() > 0;
    }

    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, 100);
    }

    public function index()
    {
        
        if (function_exists('ec_require_action')) { ec_require_action('/easychair/admin/email-templates', 'view'); }
$this->requireAccess();
        $conference = $this->conference();

        $stmt = $this->db()->prepare("
            SELECT *
            FROM conference_email_templates
            WHERE conference_id=?
              AND org_id=?
            ORDER BY 
                CASE 
                    WHEN template_key LIKE 'custom_%' THEN 2
                    ELSE 1
                END,
                template_key,
                event_key,
                id
        ");
        $stmt->execute([(int)$conference['id'], (int)$conference['org_id']]);
        $templates = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $stmt = $this->db()->prepare("
            SELECT id, short_name, title_en, title_ar, org_id
            FROM conferences
            WHERE org_id=?
            ORDER BY id DESC
        ");
        $stmt->execute([(int)$conference['org_id']]);
        $orgConferences = $stmt->fetchAll(\PDO::FETCH_ASSOC);

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

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

    public function save()
    {
        
        if (function_exists('ec_require_action')) { ec_require_action('/easychair/admin/email-templates', 'view'); }
$this->requireAccess();
        $conference = $this->conference();

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

        foreach ($templates as $id => $t) {
            $id = (int)$id;

            $templateKey = $this->normalizeKey((string)($t['template_key'] ?? ''));
            $eventKey = $this->normalizeKey((string)($t['event_key'] ?? $templateKey));

            $stmt = $this->db()->prepare("
                UPDATE conference_email_templates
                SET template_key=?,
                    event_key=?,
                    subject_ar=?,
                    subject_en=?,
                    body_ar=?,
                    body_en=?,
                    is_active=?,
                    updated_at=NOW()
                WHERE id=?
                  AND conference_id=?
                  AND org_id=?
            ");
            $stmt->execute([
                $templateKey,
                $eventKey,
                trim($t['subject_ar'] ?? ''),
                trim($t['subject_en'] ?? ''),
                trim($t['body_ar'] ?? ''),
                trim($t['body_en'] ?? ''),
                !empty($t['is_active']) ? 1 : 0,
                $id,
                (int)$conference['id'],
                (int)$conference['org_id']
            ]);
        }

        $_SESSION['flash_success'] = "Email templates saved.";
        header("Location: /easychair/admin/email-templates?saved=1");
        exit;
    }

    public function store()
    {
        
        if (function_exists('ec_require_action')) { ec_require_action('/easychair/admin/email-templates', 'view'); }
$this->requireAccess();
        $conference = $this->conference();

        $templateKey = $this->normalizeKey((string)($_POST['template_key'] ?? ''));
        $eventKey = $this->normalizeKey((string)($_POST['event_key'] ?? $templateKey));

        $subjectEn = trim((string)($_POST['subject_en'] ?? ''));
        $subjectAr = trim((string)($_POST['subject_ar'] ?? ''));
        $bodyEn = trim((string)($_POST['body_en'] ?? ''));
        $bodyAr = trim((string)($_POST['body_ar'] ?? ''));

        if ($subjectEn === '' && $subjectAr === '') {
            $_SESSION['flash_error'] = "At least one subject is required.";
            header("Location: /easychair/admin/email-templates");
            exit;
        }

        if ($bodyEn === '' && $bodyAr === '') {
            $_SESSION['flash_error'] = "At least one body is required.";
            header("Location: /easychair/admin/email-templates");
            exit;
        }

        /*
         * Your current schema does not show a UNIQUE key on template_key,
         * but we still avoid duplicate template/event keys per conference.
         */
        $stmt = $this->db()->prepare("
            SELECT id
            FROM conference_email_templates
            WHERE conference_id=?
              AND org_id=?
              AND (template_key=? OR event_key=?)
            LIMIT 1
        ");
        $stmt->execute([
            (int)$conference['id'],
            (int)$conference['org_id'],
            $templateKey,
            $eventKey
        ]);

        if ($stmt->fetchColumn()) {
            $_SESSION['flash_error'] = "Template key or event key already exists in this conference.";
            header("Location: /easychair/admin/email-templates");
            exit;
        }

        $columns = [
            'org_id',
            'conference_id',
            'template_key',
            'event_key',
            'subject_en',
            'subject_ar',
            'body_en',
            'body_ar',
            'is_active',
        ];

        $values = [
            (int)$conference['org_id'],
            (int)$conference['id'],
            $templateKey,
            $eventKey,
            $subjectEn,
            $subjectAr,
            $bodyEn,
            $bodyAr,
            !empty($_POST['is_active']) ? 1 : 0,
        ];

        if ($this->columnExists('conference_email_templates', 'created_by')) {
            $columns[] = 'created_by';
            $values[] = (int)$_SESSION['user_id'];
        }

        $placeholders = implode(',', array_fill(0, count($columns), '?'));

        $stmt = $this->db()->prepare("
            INSERT INTO conference_email_templates
            (" . implode(',', $columns) . ")
            VALUES ({$placeholders})
        ");
        $stmt->execute($values);

        $_SESSION['flash_success'] = "New email template added.";
        header("Location: /easychair/admin/email-templates?added=1");
        exit;
    }

    public function delete()
    {
        
        if (function_exists('ec_require_action')) { ec_require_action('/easychair/admin/email-templates', 'view'); }
$this->requireAccess();
        $conference = $this->conference();

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

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

        $_SESSION['flash_success'] = "Template deleted.";
        header("Location: /easychair/admin/email-templates?deleted=1");
        exit;
    }

    public function duplicate()
    {
        
        if (function_exists('ec_require_action')) { ec_require_action('/easychair/admin/email-templates', 'view'); }
$this->requireAccess();
        $conference = $this->conference();

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

        $stmt = $this->db()->prepare("
            SELECT *
            FROM conference_email_templates
            WHERE id=?
              AND conference_id=?
              AND org_id=?
            LIMIT 1
        ");
        $stmt->execute([$id, (int)$conference['id'], (int)$conference['org_id']]);
        $tpl = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$tpl) {
            exit("Template not found.");
        }

        $newKey = $this->normalizeKey(($tpl['template_key'] ?: $tpl['event_key']) . '_copy_' . date('His'));
        $newEvent = $this->normalizeKey(($tpl['event_key'] ?: $tpl['template_key']) . '_copy_' . date('His'));

        $stmt = $this->db()->prepare("
            INSERT INTO conference_email_templates
            (org_id, conference_id, template_key, event_key, subject_en, subject_ar, body_en, body_ar, is_active)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0)
        ");
        $stmt->execute([
            (int)$conference['org_id'],
            (int)$conference['id'],
            $newKey,
            $newEvent,
            (string)($tpl['subject_en'] ?? ''),
            (string)($tpl['subject_ar'] ?? ''),
            (string)($tpl['body_en'] ?? ''),
            (string)($tpl['body_ar'] ?? '')
        ]);

        $_SESSION['flash_success'] = "Template duplicated as inactive copy.";
        header("Location: /easychair/admin/email-templates?duplicated=1");
        exit;
    }
}
