<?php
namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Visit;
use App\Models\User;
use App\Services\HolidayService;
use App\Services\NotificationService;

class RemindVisits extends Command
{
    protected $signature   = 'visit:remind';
    protected $description = 'Send visit reminders for tomorrow';

    public function handle(): void
    {
        $tomorrow = now()->addDay();
        $tomorrowDate = $tomorrow->toDateString();
        $visits = Visit::where('visit_date', $tomorrowDate)
            ->where('status', 'scheduled')
            ->with(['client','technician'])
            ->get();

        $notif = new NotificationService();
        $missingPreps = [];
        foreach ($visits as $visit) {
            $techName = $visit->technician ? $visit->technician->name : '-';
            $msg = "Reminder Kunjungan\nKlien: {$visit->client->name}\nTanggal: {$visit->visit_date->format('d/m/Y')}\nTeknisi: {$techName}";

            // include note if preparation not found
            $hasPrep = \App\Models\VisitPreparation::where('visit_id', $visit->id)->exists();
            if (!$hasPrep) {
                $missingPreps[] = $visit;
                $msg .= "\n\nCatatan: Preparation belum diisi. Mohon lengkapi H-1.";
            }

            $notif->notifyUser($visit->technician, $msg, 'Reminder Kunjungan');
        }

        // If there are visits but some missing preparations, notify admins with a summary
        if (!empty($missingPreps)) {
            $admins = User::where('role', 'admin')->get();
            $summary = "Ringkasan: Terdapat ".count($missingPreps)." kunjungan besok tanpa preparation:\n";
            foreach ($missingPreps as $mv) {
                $summary .= "- Visit #{$mv->id} | {$mv->client->name} | Teknisi: ".($mv->technician?->name ?? '-')."\n";
            }
            foreach ($admins as $admin) {
                $notif->notifyUser($admin, $summary, 'Admin: Kunjungan Tanpa Preparation');
            }
        }

        if ($visits->isEmpty()) {
            $holidayService = new HolidayService();
            if ($holidayService->isHoliday($tomorrow)) {
                $this->info("No admin alert sent: {$tomorrowDate} is weekend/holiday.");
                return;
            }

            $admins = User::where('role', 'admin')->get();
            $alert = "Peringatan: Besok ({$tomorrow->format('d/m/Y')}) belum ada jadwal kunjungan. Mohon upload jadwal.";
            foreach ($admins as $admin) {
                $notif->notifyUser($admin, $alert, 'Admin: Jadwal Kunjungan Kosong');
            }

            $this->info("Sent admin alert to {$admins->count()} admin(s).");
            return;
        }

        $this->info("Sent reminders for {$visits->count()} visits.");
    }
}
