<?php

class CommunicationsController extends Controller
{
    // ═══════════════════════════════════════════
    //  NOTIFICATION TEMPLATES
    // ═══════════════════════════════════════════

    public function templates(Request $request): void
    {
        Gate::authorize('notifications.view');
        $this->view('templates/index', [
            'title'       => lang('comm.templates'),
            'breadcrumbs' => [
                ['label' => lang('comm.communications'), 'url' => '/communications/templates'],
                ['label' => lang('comm.templates')],
            ],
        ]);
    }

    public function templateCreate(Request $request): void
    {
        Gate::authorize('notifications.send');
        $db = $this->db();
        $channels = $db->fetchAll("SELECT id, channel_code, name_en, name_ar FROM notification_channels WHERE is_active = 1 ORDER BY id");

        $this->view('templates/form', [
            'title'       => lang('comm.create_template'),
            'breadcrumbs' => [
                ['label' => lang('comm.communications'), 'url' => '/communications/templates'],
                ['label' => lang('comm.templates'), 'url' => '/communications/templates'],
                ['label' => lang('comm.create_template')],
            ],
            'template'    => null,
            'channels'    => $channels,
        ]);
    }

    public function templateEdit(Request $request): void
    {
        Gate::authorize('notifications.send');
        $id = (int)$request->routeParam('id');
        $db = $this->db();

        $template = $db->fetchOne("SELECT * FROM notification_templates WHERE id = ?", [$id]);
        if (!$template) { $this->abort(404, 'Template not found'); }

        $channels = $db->fetchAll("SELECT id, channel_code, name_en, name_ar FROM notification_channels WHERE is_active = 1 ORDER BY id");

        $this->view('templates/form', [
            'title'       => lang('comm.edit_template'),
            'breadcrumbs' => [
                ['label' => lang('comm.communications'), 'url' => '/communications/templates'],
                ['label' => lang('comm.templates'), 'url' => '/communications/templates'],
                ['label' => lang('comm.edit_template')],
            ],
            'template'    => $template,
            'channels'    => $channels,
        ]);
    }

    // ═══════════════════════════════════════════
    //  CHANNELS
    // ═══════════════════════════════════════════

    public function channels(Request $request): void
    {
        Gate::authorize('notifications.view');
        $this->view('channels/index', [
            'title'       => lang('comm.channels'),
            'breadcrumbs' => [
                ['label' => lang('comm.communications'), 'url' => '/communications/templates'],
                ['label' => lang('comm.channels')],
            ],
        ]);
    }

    public function channelCreate(Request $request): void
    {
        Gate::authorize('notifications.send');
        $this->view('channels/form', [
            'title'       => lang('comm.create_channel'),
            'breadcrumbs' => [
                ['label' => lang('comm.communications'), 'url' => '/communications/templates'],
                ['label' => lang('comm.channels'), 'url' => '/communications/channels'],
                ['label' => lang('comm.create_channel')],
            ],
            'channel'     => null,
        ]);
    }

    public function channelEdit(Request $request): void
    {
        Gate::authorize('notifications.send');
        $id = (int)$request->routeParam('id');
        $channel = $this->db()->fetchOne("SELECT * FROM notification_channels WHERE id = ?", [$id]);
        if (!$channel) { $this->abort(404, 'Channel not found'); }

        $this->view('channels/form', [
            'title'       => lang('comm.edit_channel'),
            'breadcrumbs' => [
                ['label' => lang('comm.communications'), 'url' => '/communications/templates'],
                ['label' => lang('comm.channels'), 'url' => '/communications/channels'],
                ['label' => lang('comm.edit_channel')],
            ],
            'channel'     => $channel,
        ]);
    }

    // ═══════════════════════════════════════════
    //  TRIGGERS
    // ═══════════════════════════════════════════

    public function triggers(Request $request): void
    {
        Gate::authorize('notifications.view');
        $this->view('triggers/index', [
            'title'       => lang('comm.triggers'),
            'breadcrumbs' => [
                ['label' => lang('comm.communications'), 'url' => '/communications/templates'],
                ['label' => lang('comm.triggers')],
            ],
        ]);
    }

    public function triggerCreate(Request $request): void
    {
        Gate::authorize('notifications.send');
        $db = $this->db();
        $templates = $db->fetchAll("SELECT id, template_code, name_en, name_ar FROM notification_templates WHERE is_active = 1 ORDER BY name_en");

        $this->view('triggers/form', [
            'title'       => lang('comm.create_trigger'),
            'breadcrumbs' => [
                ['label' => lang('comm.communications'), 'url' => '/communications/templates'],
                ['label' => lang('comm.triggers'), 'url' => '/communications/triggers'],
                ['label' => lang('comm.create_trigger')],
            ],
            'trigger'     => null,
            'templates'   => $templates,
        ]);
    }

    public function triggerEdit(Request $request): void
    {
        Gate::authorize('notifications.send');
        $id = (int)$request->routeParam('id');
        $db = $this->db();

        $trigger = $db->fetchOne("SELECT * FROM notification_triggers WHERE id = ?", [$id]);
        if (!$trigger) { $this->abort(404, 'Trigger not found'); }

        $templates = $db->fetchAll("SELECT id, template_code, name_en, name_ar FROM notification_templates WHERE is_active = 1 ORDER BY name_en");

        $this->view('triggers/form', [
            'title'       => lang('comm.edit_trigger'),
            'breadcrumbs' => [
                ['label' => lang('comm.communications'), 'url' => '/communications/templates'],
                ['label' => lang('comm.triggers'), 'url' => '/communications/triggers'],
                ['label' => lang('comm.edit_trigger')],
            ],
            'trigger'     => $trigger,
            'templates'   => $templates,
        ]);
    }

    // ═══════════════════════════════════════════
    //  QUEUE
    // ═══════════════════════════════════════════

    public function queue(Request $request): void
    {
        Gate::authorize('notifications.send');
        $db = $this->db();
        $stats = [
            'queued'     => (int)$db->fetchColumn("SELECT COUNT(*) FROM notification_queue WHERE status = 'queued'"),
            'processing' => (int)$db->fetchColumn("SELECT COUNT(*) FROM notification_queue WHERE status = 'processing'"),
            'sent'       => (int)$db->fetchColumn("SELECT COUNT(*) FROM notification_queue WHERE status = 'sent' AND DATE(sent_at) = CURDATE()"),
            'failed'     => (int)$db->fetchColumn("SELECT COUNT(*) FROM notification_queue WHERE status = 'failed'"),
        ];

        $this->view('queue/index', [
            'title'       => lang('comm.notification_queue'),
            'breadcrumbs' => [
                ['label' => lang('comm.communications'), 'url' => '/communications/templates'],
                ['label' => lang('comm.notification_queue')],
            ],
            'stats'       => $stats,
        ]);
    }

    // ═══════════════════════════════════════════
    //  SENT
    // ═══════════════════════════════════════════

    public function sent(Request $request): void
    {
        Gate::authorize('notifications.view');
        $this->view('sent/index', [
            'title'       => lang('comm.sent_notifications'),
            'breadcrumbs' => [
                ['label' => lang('comm.communications'), 'url' => '/communications/templates'],
                ['label' => lang('comm.sent_notifications')],
            ],
        ]);
    }

    // ═══════════════════════════════════════════
    //  BULK COMMUNICATIONS
    // ═══════════════════════════════════════════

    public function bulk(Request $request): void
    {
        Gate::authorize('notifications.bulk');
        $this->view('bulk/index', [
            'title'       => lang('comm.bulk_communications'),
            'breadcrumbs' => [
                ['label' => lang('comm.communications'), 'url' => '/communications/templates'],
                ['label' => lang('comm.bulk_communications')],
            ],
        ]);
    }

    public function bulkCreate(Request $request): void
    {
        Gate::authorize('notifications.bulk');
        $db = $this->db();
        $channels  = $db->fetchAll("SELECT id, channel_code, name_en, name_ar FROM notification_channels WHERE is_active = 1 ORDER BY id");
        $templates = $db->fetchAll("SELECT id, template_code, name_en, name_ar FROM notification_templates WHERE is_active = 1 ORDER BY name_en");
        $memTypes  = $db->fetchAll("SELECT id, type_code, name_en, name_ar FROM membership_types WHERE is_active = 1 ORDER BY sort_order");

        $this->view('bulk/form', [
            'title'       => lang('comm.create_bulk'),
            'breadcrumbs' => [
                ['label' => lang('comm.communications'), 'url' => '/communications/templates'],
                ['label' => lang('comm.bulk_communications'), 'url' => '/communications/bulk'],
                ['label' => lang('comm.create_bulk')],
            ],
            'channels'    => $channels,
            'templates'   => $templates,
            'memTypes'    => $memTypes,
        ]);
    }

    public function bulkView(Request $request): void
    {
        Gate::authorize('notifications.bulk');
        $id = (int)$request->routeParam('id');
        $db = $this->db();

        $campaign = $db->fetchOne(
            "SELECT bc.*, nc.name_en AS channel_name
             FROM bulk_communications bc
             LEFT JOIN notification_channels nc ON bc.channel_id = nc.id
             WHERE bc.id = ?", [$id]
        );
        if (!$campaign) { $this->abort(404, 'Campaign not found'); }

        $this->view('bulk/view', [
            'title'       => lang('comm.view_campaign'),
            'breadcrumbs' => [
                ['label' => lang('comm.communications'), 'url' => '/communications/templates'],
                ['label' => lang('comm.bulk_communications'), 'url' => '/communications/bulk'],
                ['label' => $campaign['campaign_name']],
            ],
            'campaign'    => $campaign,
        ]);
    }

    // ═══════════════════════════════════════════
    //  LOGS
    // ═══════════════════════════════════════════

    public function emailLog(Request $request): void
    {
        Gate::authorize('notifications.view');
        $this->view('logs/email', [
            'title'       => lang('comm.email_log'),
            'breadcrumbs' => [
                ['label' => lang('comm.communications'), 'url' => '/communications/templates'],
                ['label' => lang('comm.email_log')],
            ],
        ]);
    }

    public function smsLog(Request $request): void
    {
        Gate::authorize('notifications.view');
        $this->view('logs/sms', [
            'title'       => lang('comm.sms_log'),
            'breadcrumbs' => [
                ['label' => lang('comm.communications'), 'url' => '/communications/templates'],
                ['label' => lang('comm.sms_log')],
            ],
        ]);
    }

    // ═══════════════════════════════════════════
    //  ANNOUNCEMENTS
    // ═══════════════════════════════════════════

    public function announcements(Request $request): void
    {
        Gate::authorize('notifications.send');
        $this->view('announcements/index', [
            'title'       => lang('comm.announcements'),
            'breadcrumbs' => [
                ['label' => lang('comm.communications'), 'url' => '/communications/templates'],
                ['label' => lang('comm.announcements')],
            ],
        ]);
    }

    public function announcementCreate(Request $request): void
    {
        Gate::authorize('notifications.send');
        $memTypes = $this->db()->fetchAll("SELECT id, type_code, name_en, name_ar FROM membership_types WHERE is_active = 1 ORDER BY sort_order");

        $this->view('announcements/form', [
            'title'        => lang('comm.create_announcement'),
            'breadcrumbs'  => [
                ['label' => lang('comm.communications'), 'url' => '/communications/templates'],
                ['label' => lang('comm.announcements'), 'url' => '/communications/announcements'],
                ['label' => lang('comm.create_announcement')],
            ],
            'announcement' => null,
            'memTypes'     => $memTypes,
        ]);
    }

    public function announcementEdit(Request $request): void
    {
        Gate::authorize('notifications.send');
        $id = (int)$request->routeParam('id');
        $announcement = $this->db()->fetchOne("SELECT * FROM announcements WHERE id = ?", [$id]);
        if (!$announcement) { $this->abort(404, 'Announcement not found'); }

        $memTypes = $this->db()->fetchAll("SELECT id, type_code, name_en, name_ar FROM membership_types WHERE is_active = 1 ORDER BY sort_order");

        $this->view('announcements/form', [
            'title'        => lang('comm.edit_announcement'),
            'breadcrumbs'  => [
                ['label' => lang('comm.communications'), 'url' => '/communications/templates'],
                ['label' => lang('comm.announcements'), 'url' => '/communications/announcements'],
                ['label' => lang('comm.edit_announcement')],
            ],
            'announcement' => $announcement,
            'memTypes'     => $memTypes,
        ]);
    }

    // ═══════════════════════════════════════════
    //  DOCUMENT TEMPLATES
    // ═══════════════════════════════════════════

    public function docTemplates(Request $request): void
    {
        Gate::authorize('documents.view');
        $this->view('documents/templates_index', [
            'title'       => lang('comm.document_templates'),
            'breadcrumbs' => [
                ['label' => lang('comm.communications'), 'url' => '/communications/templates'],
                ['label' => lang('comm.document_templates')],
            ],
        ]);
    }

    public function docTemplateCreate(Request $request): void
    {
        Gate::authorize('documents.manage');
        $this->view('documents/template_form', [
            'title'       => lang('comm.create_doc_template'),
            'breadcrumbs' => [
                ['label' => lang('comm.communications'), 'url' => '/communications/templates'],
                ['label' => lang('comm.document_templates'), 'url' => '/communications/document-templates'],
                ['label' => lang('comm.create_doc_template')],
            ],
            'template'    => null,
        ]);
    }

    public function docTemplateEdit(Request $request): void
    {
        Gate::authorize('documents.manage');
        $id = (int)$request->routeParam('id');
        $template = $this->db()->fetchOne("SELECT * FROM document_templates WHERE id = ?", [$id]);
        if (!$template) { $this->abort(404, 'Document template not found'); }

        $this->view('documents/template_form', [
            'title'       => lang('comm.edit_doc_template'),
            'breadcrumbs' => [
                ['label' => lang('comm.communications'), 'url' => '/communications/templates'],
                ['label' => lang('comm.document_templates'), 'url' => '/communications/document-templates'],
                ['label' => lang('comm.edit_doc_template')],
            ],
            'template'    => $template,
        ]);
    }

    // ═══════════════════════════════════════════
    //  DOCUMENT GENERATION
    // ═══════════════════════════════════════════

    public function generateDocument(Request $request): void
    {
        Gate::authorize('documents.manage');
        $db = $this->db();
        $templates = $db->fetchAll("SELECT id, template_code, name_en, name_ar, category, template_type FROM document_templates WHERE is_active = 1 ORDER BY category, name_en");
        $recentDocs = $db->fetchAll(
            "SELECT gd.*, dt.name_en AS template_name, m.membership_number, m.full_name_en AS member_name
             FROM generated_documents gd
             LEFT JOIN document_templates dt ON gd.template_id = dt.id
             LEFT JOIN members m ON gd.member_id = m.id
             ORDER BY gd.generated_at DESC LIMIT 20"
        );

        $this->view('documents/generate', [
            'title'       => lang('comm.generate_document'),
            'breadcrumbs' => [
                ['label' => lang('comm.communications'), 'url' => '/communications/templates'],
                ['label' => lang('comm.generate_document')],
            ],
            'templates'   => $templates,
            'recentDocs'  => $recentDocs,
        ]);
    }
}