<?php
declare(strict_types=1);

namespace App\Modules\Notifications\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Notifications\Models\NotificationTrigger;
use App\Modules\Notifications\Models\SmsTemplate;

class TriggerController extends Controller
{
    /**
     * List all notification triggers.
     */
    public function index(Request $request): Response
    {
        $this->authorize('notification.triggers.view');

        $triggers = NotificationTrigger::getAll();
        return $this->view('Notifications.Views.triggers', ['triggers' => $triggers]);
    }

    /**
     * Show create form for a new trigger.
     */
    public function create(Request $request): Response
    {
        $this->authorize('notification.triggers.manage');

        $templates = SmsTemplate::getAll();
        $trigger = null;

        return $this->view('Notifications.Views.trigger_edit', [
            'trigger'   => $trigger,
            'templates' => $templates,
            'isEdit'    => false,
        ]);
    }

    /**
     * Store a new trigger.
     */
    public function store(Request $request): Response
    {
        $this->authorize('notification.triggers.manage');

        $data = [
            'trigger_code'    => trim((string) $request->post('trigger_code', '')),
            'trigger_name_ar' => trim((string) $request->post('trigger_name_ar', '')),
            'event_name'      => trim((string) $request->post('event_name', '')),
            'template_id'     => $request->post('template_id') ? (int) $request->post('template_id') : null,
            'is_active'       => (int) $request->post('is_active', 1),
            'channel'         => trim((string) $request->post('channel', 'sms')),
            'recipient_type'  => trim((string) $request->post('recipient_type', 'player')),
            'priority'        => (int) $request->post('priority', 0),
        ];

        // Validate required fields
        if ($data['trigger_code'] === '' || $data['trigger_name_ar'] === '' || $data['event_name'] === '') {
            return $this->redirect('/notifications/triggers/create')->withError('جميع الحقول المطلوبة يجب ملؤها');
        }

        // Check for duplicate trigger code
        $existing = NotificationTrigger::findByCode($data['trigger_code']);
        if ($existing) {
            return $this->redirect('/notifications/triggers/create')->withError('كود المشغل موجود بالفعل');
        }

        // Build config JSON
        $config = [];
        $delayMinutes = (int) $request->post('delay_minutes', 0);
        if ($delayMinutes > 0) {
            $config['delay_minutes'] = $delayMinutes;
        }
        $maxAttempts = (int) $request->post('max_attempts', 3);
        if ($maxAttempts !== 3) {
            $config['max_attempts'] = $maxAttempts;
        }
        $data['config_json'] = !empty($config) ? json_encode($config, JSON_UNESCAPED_UNICODE) : null;

        $db = App::getInstance()->db();
        $db->insert('notification_triggers', array_merge($data, [
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]));

        return $this->redirect('/notifications/triggers')->withSuccess('تم إنشاء المشغل بنجاح');
    }

    /**
     * Show edit form for an existing trigger.
     */
    public function edit(Request $request, string $id): Response
    {
        $this->authorize('notification.triggers.manage');

        $db = App::getInstance()->db();
        $trigger = $db->selectOne("SELECT * FROM notification_triggers WHERE id = ?", [(int) $id]);
        if (!$trigger) {
            return $this->redirect('/notifications/triggers')->withError('المشغل غير موجود');
        }

        $templates = SmsTemplate::getAll();

        return $this->view('Notifications.Views.trigger_edit', [
            'trigger'   => $trigger,
            'templates' => $templates,
            'isEdit'    => true,
        ]);
    }

    /**
     * Update an existing trigger.
     */
    public function update(Request $request, string $id): Response
    {
        $this->authorize('notification.triggers.manage');

        $db = App::getInstance()->db();
        $trigger = $db->selectOne("SELECT * FROM notification_triggers WHERE id = ?", [(int) $id]);
        if (!$trigger) {
            return $this->redirect('/notifications/triggers')->withError('المشغل غير موجود');
        }

        $data = [
            'trigger_name_ar' => trim((string) $request->post('trigger_name_ar', '')),
            'event_name'      => trim((string) $request->post('event_name', '')),
            'template_id'     => $request->post('template_id') ? (int) $request->post('template_id') : null,
            'is_active'       => (int) $request->post('is_active', 1),
            'channel'         => trim((string) $request->post('channel', 'sms')),
            'recipient_type'  => trim((string) $request->post('recipient_type', 'player')),
            'priority'        => (int) $request->post('priority', 0),
            'updated_at'      => date('Y-m-d H:i:s'),
        ];

        if ($data['trigger_name_ar'] === '' || $data['event_name'] === '') {
            return $this->redirect("/notifications/triggers/{$id}/edit")->withError('جميع الحقول المطلوبة يجب ملؤها');
        }

        // Build config JSON
        $config = [];
        $delayMinutes = (int) $request->post('delay_minutes', 0);
        if ($delayMinutes > 0) {
            $config['delay_minutes'] = $delayMinutes;
        }
        $maxAttempts = (int) $request->post('max_attempts', 3);
        if ($maxAttempts !== 3) {
            $config['max_attempts'] = $maxAttempts;
        }
        $data['config_json'] = !empty($config) ? json_encode($config, JSON_UNESCAPED_UNICODE) : null;

        $db->update('notification_triggers', $data, '`id` = ?', [(int) $id]);

        return $this->redirect('/notifications/triggers')->withSuccess('تم تحديث المشغل بنجاح');
    }

    /**
     * Toggle active status of a trigger (AJAX-friendly).
     */
    public function toggle(Request $request, string $id): Response
    {
        $this->authorize('notification.triggers.manage');

        $success = NotificationTrigger::toggleActive((int) $id);
        if (!$success) {
            return $this->redirect('/notifications/triggers')->withError('المشغل غير موجود');
        }

        return $this->redirect('/notifications/triggers')->withSuccess('تم تحديث حالة المشغل');
    }
}
