<?php
namespace App\Controllers;

use App\Core\Database;

class AdminWorkflowNotificationRulesController
{
    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;
    }

    public function index()
    {
        $this->requireAccess();
        $conference = $this->conference();

        $stmt = $this->db()->prepare("
            SELECT *
            FROM conference_workflow_email_rules
            WHERE conference_id=?
              AND org_id=?
            ORDER BY FIELD(stage_key,'revision_required','accepted','rejected','camera_ready'), stage_key
        ");
        $stmt->execute([(int)$conference['id'], (int)$conference['org_id']]);
        $rules = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $stmt = $this->db()->prepare("
            SELECT template_key, event_key, subject_en, subject_ar
            FROM conference_email_templates
            WHERE conference_id=?
              AND org_id=?
              AND is_active=1
            ORDER BY template_key, event_key
        ");
        $stmt->execute([(int)$conference['id'], (int)$conference['org_id']]);
        $templates = $stmt->fetchAll(\PDO::FETCH_ASSOC);

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

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

    public function save()
    {
        $this->requireAccess();
        $conference = $this->conference();

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

        foreach ($rules as $id => $r) {
            $id = (int)$id;
            $templateKey = trim((string)($r['template_key'] ?? ''));
            $lang = trim((string)($r['lang'] ?? 'en'));

            if (!in_array($lang, ['en','ar'], true)) {
                $lang = 'en';
            }

            if ($templateKey === '') {
                continue;
            }

            $stmt = $this->db()->prepare("
                UPDATE conference_workflow_email_rules
                SET template_key=?,
                    lang=?,
                    is_active=?,
                    updated_at=NOW()
                WHERE id=?
                  AND conference_id=?
                  AND org_id=?
            ");
            $stmt->execute([
                $templateKey,
                $lang,
                !empty($r['is_active']) ? 1 : 0,
                $id,
                (int)$conference['id'],
                (int)$conference['org_id']
            ]);
        }

        $_SESSION['flash_success'] = 'Workflow notification rules saved.';
        header("Location: /easychair/admin/workflow-notifications?saved=1");
        exit;
    }

    public function store()
    {
        $this->requireAccess();
        $conference = $this->conference();

        $stageKey = strtolower(trim((string)($_POST['stage_key'] ?? '')));
        $stageKey = preg_replace('/[^a-z0-9_\-]+/', '_', $stageKey);
        $stageKey = trim($stageKey, '_-');

        $templateKey = trim((string)($_POST['template_key'] ?? ''));
        $lang = trim((string)($_POST['lang'] ?? 'en'));

        if ($stageKey === '' || $templateKey === '') {
            $_SESSION['flash_error'] = 'Stage key and template are required.';
            header("Location: /easychair/admin/workflow-notifications");
            exit;
        }

        if (!in_array($lang, ['en','ar'], true)) {
            $lang = 'en';
        }

        $stmt = $this->db()->prepare("
            INSERT INTO conference_workflow_email_rules
            (org_id, conference_id, stage_key, template_key, lang, is_active, created_by)
            VALUES (?, ?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                template_key=VALUES(template_key),
                lang=VALUES(lang),
                is_active=VALUES(is_active),
                updated_at=NOW()
        ");
        $stmt->execute([
            (int)$conference['org_id'],
            (int)$conference['id'],
            $stageKey,
            $templateKey,
            $lang,
            !empty($_POST['is_active']) ? 1 : 0,
            (int)$_SESSION['user_id']
        ]);

        $_SESSION['flash_success'] = 'Workflow notification rule added.';
        header("Location: /easychair/admin/workflow-notifications?added=1");
        exit;
    }

    public function delete()
    {
        $this->requireAccess();
        $conference = $this->conference();

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

        $_SESSION['flash_success'] = 'Workflow notification rule deleted.';
        header("Location: /easychair/admin/workflow-notifications?deleted=1");
        exit;
    }
}
