<?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\SmsTemplate;
use App\Modules\Notifications\Models\SmsLog;
use App\Modules\Notifications\Services\SmsService;

class NotificationController extends Controller
{
    public function templates(Request $request): Response
    {
        $templates = SmsTemplate::getAll();
        return $this->view('Notifications.Views.templates', ['templates' => $templates]);
    }

    public function updateTemplate(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();
        $template = $db->selectOne("SELECT * FROM sms_templates WHERE id = ?", [(int) $id]);
        if (!$template) return $this->redirect('/notifications/templates')->withError('القالب غير موجود');

        $messageAr = trim((string) $request->post('message_template_ar', ''));
        if ($messageAr === '') return $this->redirect('/notifications/templates')->withError('نص الرسالة مطلوب');

        $db->update('sms_templates', [
            'message_template_ar' => $messageAr,
            'name_ar'             => trim((string) $request->post('name_ar', $template['name_ar'])),
            'is_active'           => (int) $request->post('is_active', 1),
            'updated_at'          => date('Y-m-d H:i:s'),
        ], '`id` = ?', [(int) $id]);

        return $this->redirect('/notifications/templates')->withSuccess('تم تحديث القالب');
    }

    public function log(Request $request): Response
    {
        $filters = [
            'search'  => trim((string) $request->get('q', '')),
            'status'  => $request->get('status', ''),
            'date_from' => $request->get('date_from', ''),
            'date_to'   => $request->get('date_to', ''),
        ];
        $page = max(1, (int) $request->get('page', 1));
        $result = SmsLog::search($filters, 30, $page);

        return $this->view('Notifications.Views.log', [
            'rows'       => $result['data'],
            'pagination' => $result['pagination'],
            'filters'    => $filters,
        ]);
    }

    public function sendForm(Request $request): Response
    {
        $templates = SmsTemplate::getAll();
        return $this->view('Notifications.Views.send', ['templates' => $templates]);
    }

    public function send(Request $request): Response
    {
        $phone = trim((string) $request->post('phone_number', ''));
        $memberId = $request->post('member_id') ? (int) $request->post('member_id') : null;
        $templateId = $request->post('template_id') ? (int) $request->post('template_id') : null;
        $customMessage = trim((string) $request->post('custom_message', ''));

        if ($phone === '') return $this->redirect('/notifications/send')->withError('رقم الهاتف مطلوب');

        $message = $customMessage;
        if ($templateId && $message === '') {
            $template = App::getInstance()->db()->selectOne("SELECT * FROM sms_templates WHERE id = ?", [$templateId]);
            $message = $template ? $template['message_template_ar'] : '';
        }
        if ($message === '') return $this->redirect('/notifications/send')->withError('نص الرسالة مطلوب');

        $result = SmsService::send($phone, $message, $memberId, $templateId);

        if ($result['success']) {
            return $this->redirect('/notifications/log')->withSuccess('تم إرسال الرسالة بنجاح');
        }
        return $this->redirect('/notifications/send')->withError('فشل الإرسال: ' . ($result['error'] ?? 'خطأ غير معروف'));
    }

    public function sendBulk(Request $request): Response
    {
        $filter = $request->post('filter', 'all_active');
        $templateId = (int) $request->post('template_id', 0);
        $customMessage = trim((string) $request->post('custom_message', ''));

        $db = App::getInstance()->db();
        $template = $templateId ? $db->selectOne("SELECT * FROM sms_templates WHERE id = ?", [$templateId]) : null;
        $messageTemplate = $customMessage ?: ($template ? $template['message_template_ar'] : '');
        if ($messageTemplate === '') return $this->redirect('/notifications/send')->withError('نص الرسالة مطلوب');

        $members = [];
        switch ($filter) {
            case 'all_active':
                $members = $db->select("SELECT id, full_name_ar, phone_mobile FROM members WHERE status = 'active' AND is_archived = 0 AND phone_mobile IS NOT NULL");
                break;
            case 'unpaid_subscription':
                $year = self::getCurrentFinancialYear();
                $members = $db->select(
                    "SELECT DISTINCT m.id, m.full_name_ar, m.phone_mobile FROM members m
                     JOIN subscriptions s ON s.member_id = m.id
                     WHERE s.financial_year = ? AND s.status IN ('pending','overdue')
                     AND m.is_archived = 0 AND m.phone_mobile IS NOT NULL",
                    [$year]
                );
                break;
            case 'overdue_installments':
                $members = $db->select(
                    "SELECT DISTINCT m.id, m.full_name_ar, m.phone_mobile FROM members m
                     JOIN installment_plans p ON p.member_id = m.id
                     JOIN installment_schedule s ON s.installment_plan_id = p.id
                     WHERE p.status = 'active' AND s.status = 'pending' AND s.due_date < CURDATE()
                     AND m.is_archived = 0 AND m.phone_mobile IS NOT NULL"
                );
                break;
            default:
                $members = $db->select("SELECT id, full_name_ar, phone_mobile FROM members WHERE status = 'active' AND is_archived = 0 AND phone_mobile IS NOT NULL");
        }

        $sent = 0;
        foreach ($members as $m) {
            $msg = str_replace('{member_name}', $m['full_name_ar'], $messageTemplate);
            SmsService::queue($m['phone_mobile'], $msg, (int) $m['id'], $templateId ?: null);
            $sent++;
        }

        return $this->redirect('/notifications/log')->withSuccess("تم جدولة {$sent} رسالة للإرسال");
    }

    private static function getCurrentFinancialYear(): string
    {
        $month = (int) date('n');
        $year = (int) date('Y');
        return $month >= 7 ? $year . '/' . ($year + 1) : ($year - 1) . '/' . $year;
    }
}