<?php
declare(strict_types=1);
namespace App\Services;

use App\Repositories\QueueRepository;
use App\Repositories\SettingRepository;

final class QueueService {
    public function __construct(
        private ?QueueRepository $queue = null,
        private ?SettingRepository $settings = null,
        private ?WhatsAppService $whatsApp = null,
        private ?AuditService $audit = null,
    ) {
        $this->queue ??= new QueueRepository();
        $this->settings ??= new SettingRepository();
        $this->whatsApp ??= new WhatsAppService($this->settings);
        $this->audit ??= new AuditService();
    }

    public function callNext(): ?array {
        $ticket = $this->queue->callNext();
        if ($ticket) {
            $this->audit->log('queue', 'call_next', (int)$ticket['id'], ['ticket_no' => $ticket['ticket_no']]);
            if (!empty($ticket['customer_phone'])) {
                $template = $this->settings->get('queue_now_template', "تذكرتك {ticket_no}، حان دورك الآن. يرجى التوجه مباشرة إلى الرسبشن.");
                $message = $this->whatsApp->renderTemplate($template, [
                    'name' => (string)$ticket['ticket_no'],
                    'ticket_no' => (string)$ticket['ticket_no'],
                    'remaining' => '0',
                    'phone' => (string)($ticket['customer_phone'] ?? ''),
                ]);
                $result = $this->whatsApp->send((string)$ticket['customer_phone'], $message);
                $this->queue->logNotification((int)$ticket['id'], (string)$ticket['customer_phone'], 0, $message, (string)$result['status'], (string)$result['response']);
            }
            $this->sendThresholdReminders();
        }
        return $ticket;
    }

    public function completeCurrent(): ?array {
        $current = $this->queue->getCurrentServing();
        if ($current) {
            $amount = (float)$this->settings->get('queue_ticket_price', '0');
            $this->queue->markDone((int)$current['id'], $amount);
            $this->audit->log('queue', 'mark_done', (int)$current['id'], ['ticket_no' => $current['ticket_no'], 'amount' => $amount]);
        }
        return $current;
    }

    public function skipCurrent(): ?array {
        $ticket = $this->queue->skipCurrent();
        if ($ticket) $this->audit->log('queue', 'skip_current', (int)$ticket['id'], ['ticket_no' => $ticket['ticket_no']]);
        return $ticket;
    }

    public function recallSkipped(int $ticketId): ?array {
        $ticket = $this->queue->recallSkipped($ticketId);
        if ($ticket) {
            $this->audit->log('queue', 'recall_skipped', (int)$ticket['id'], ['ticket_no' => $ticket['ticket_no']]);
            if (!empty($ticket['customer_phone'])) {
                $template = $this->settings->get('queue_now_template', "تذكرتك {ticket_no}، حان دورك الآن. يرجى التوجه مباشرة إلى الرسبشن.");
                $message = $this->whatsApp->renderTemplate($template, [
                    'name' => (string)$ticket['ticket_no'],
                    'ticket_no' => (string)$ticket['ticket_no'],
                    'remaining' => '0',
                    'phone' => (string)($ticket['customer_phone'] ?? ''),
                ]);
                $result = $this->whatsApp->send((string)$ticket['customer_phone'], $message);
                $this->queue->logNotification((int)$ticket['id'], (string)$ticket['customer_phone'], 0, $message, (string)$result['status'], (string)$result['response']);
            }
        }
        return $ticket;
    }

    public function openNewDay(): void {
        $this->queue->resetOpenSession();
        $this->audit->log('queue', 'open_new_day');
    }

    public function resetSession(): void {
        $this->openNewDay();
    }

    public function sendThresholdReminders(): void {
        $threshold = max(1, (int)$this->settings->get('queue_notify_before', '3'));
        $template = $this->settings->get('queue_message_template', "مرحباً {ticket_no}\nتبقى أمامك {remaining} أدوار\nيرجى التوجه قريباً.");
        $rows = $this->queue->ticketsNeedingReminder($threshold);
        foreach ($rows as $row) {
            $remaining = (int)$row['remaining_count'];
            $message = $this->whatsApp->renderTemplate($template, [
                'name' => $row['ticket_no'],
                'ticket_no' => $row['ticket_no'],
                'remaining' => (string)$remaining,
                'phone' => $row['customer_phone'],
            ]);
            if ($this->queue->notificationAlreadySent((int)$row['id'], $remaining, sha1($message))) {
                continue;
            }
            $result = $this->whatsApp->send((string)$row['customer_phone'], $message);
            $this->queue->logNotification((int)$row['id'], (string)$row['customer_phone'], $remaining, $message, (string)$result['status'], (string)$result['response']);
        }
    }
}
