<?php
namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class NotificationService
{
    public function sendWhatsapp(string $number, string $message): bool
    {
        $token = config('services.fonnte.token');
        if (!$token) return false;
        if (!$token) {
            Log::warning('WhatsApp: Fonnte token missing');
            return false;
        }

        try {
            $res = Http::withHeaders(['Authorization' => $token])
                ->post('https://api.fonnte.com/send', [
                    'target'  => $number,
                    'message' => $message,
                ]);

            if (!$res->successful()) {
                Log::error('WhatsApp send failed', ['status' => $res->status(), 'body' => $res->body()]);
                return false;
            }

            return true;
        } catch (\Exception $e) {
            Log::error('WA error: '.$e->getMessage());
            return false;
        }
    }

    public function sendTelegram(string $chatId, string $message): bool
    {
        $token = config('services.telegram.bot_token');
        if (!$token) {
            Log::warning('Telegram: bot token missing');
            return false;
        }

        try {
            $res = Http::post("https://api.telegram.org/bot{$token}/sendMessage", [
                'chat_id'    => $chatId,
                'text'       => $message,
                'parse_mode' => 'HTML',
            ]);

            if (!$res->successful()) {
                Log::error('Telegram send failed', ['status' => $res->status(), 'body' => $res->body()]);
                return false;
            }

            return true;
        } catch (\Exception $e) {
            Log::error('Telegram error: '.$e->getMessage());
            return false;
        }
    }

    public function sendEmail(string $to, string $subject, string $body): bool
    {
        try {
            Mail::raw($body, function ($m) use ($to, $subject) {
                $m->to($to)->subject($subject);
            });
            return true;
        } catch (\Exception $e) {
            Log::error('Email error: '.$e->getMessage());
            // Still count as "sent" if Mail is not configured, to avoid blocking
            return true;
        }
    }

    private function notifyContact(?string $telegramId, ?string $whatsappNumber, ?string $email, string $message, string $subject = 'Notifikasi'): void
    {
        try {
            if ($telegramId && $this->sendTelegram($telegramId, $message)) {
                return;
            }
        } catch (\Exception $e) {
            Log::error("notifyContact telegram error: ".$e->getMessage());
        }
        
        try {
            if ($whatsappNumber && $this->sendWhatsapp($whatsappNumber, $message)) {
                return;
            }
        } catch (\Exception $e) {
            Log::error("notifyContact whatsapp error: ".$e->getMessage());
        }
        
        try {
            if ($email) {
                $this->sendEmail($email, $subject, $message);
            }
        } catch (\Exception $e) {
            Log::error("notifyContact email error: ".$e->getMessage());
        }
    }

    public function notifyUser(?\App\Models\User $user, string $message, string $subject = 'Notifikasi'): void
    {
        if (!$user) {
            Log::info('notifyUser: user is null');
            return;
        }
        
        try {
            $this->notifyContact($user->telegram_chat_id, $user->whatsapp_number, $user->email, $message, $subject);
        } catch (\Exception $e) {
            Log::error("notifyUser error: ".$e->getMessage());
        }
    }

    public function notifyTicketCreated(\App\Models\Ticket $ticket): void
    {
        try {
            $client = $ticket->client;
            $msg    = "Tiket Baru: #{$ticket->ticket_number}\nSubjek: {$ticket->subject}\nPrioritas: ".strtoupper($ticket->priority)."\n\nTim kami akan segera menangani.";
            if ($client->email)     $this->sendEmail($client->email, "Tiket Baru: #{$ticket->ticket_number}", $msg);
            if ($client->pic_phone) $this->sendWhatsapp($client->pic_phone, $msg);
        } catch (\Exception $e) {
            Log::error("notifyTicketCreated error: ".$e->getMessage());
        }
    }

    public function notifyTicketResolved(\App\Models\Ticket $ticket): void
    {
        try {
            $survey = $ticket->csat;
            $link   = $survey ? url('/csat/'.$survey->token) : '';
            $msg    = "Tiket #{$ticket->ticket_number} telah SELESAI.\n\nMohon berikan penilaian:\n{$link}";
            $client = $ticket->client;
            if ($client->email)     $this->sendEmail($client->email, "Tiket Selesai: #{$ticket->ticket_number}", $msg);
            if ($client->pic_phone) $this->sendWhatsapp($client->pic_phone, $msg);
        } catch (\Exception $e) {
            Log::error("notifyTicketResolved error: ".$e->getMessage());
        }
    }

    public function notifyNewComment(\App\Models\Ticket $ticket, \App\Models\TicketComment $comment): void
    {
        try {
            if ($comment->is_internal) return;
            $client = $ticket->client;
            $msg    = "Komentar baru pada tiket #{$ticket->ticket_number}:\n\n{$comment->body}";
            if ($client->pic_phone) $this->sendWhatsapp($client->pic_phone, $msg);
        } catch (\Exception $e) {
            Log::error("notifyNewComment error: ".$e->getMessage());
        }
    }

    public function notifyVisitScheduled(\App\Models\Visit $visit): void
    {
        if (!$visit->technician) {
            Log::info('notifyVisitScheduled: No technician assigned');
            return;
        }
        
        $techName = $visit->technician->name;
        $msg = "Kunjungan Terjadwal\nKlien: {$visit->client->name}\nTanggal: {$visit->visit_date->format('d/m/Y')}\nJam: ".($visit->visit_time_start ?: '-')."\nTeknisi: {$techName}";
        
        try {
            $this->notifyUser($visit->technician, $msg, 'Reminder Kunjungan');
        } catch (\Exception $e) {
            Log::error("notifyVisitScheduled error: ".$e->getMessage());
        }
    }

    public function notifyInvoiceSent(\App\Models\Invoice $invoice): void
    {
        try {
            $msg = "Invoice #{$invoice->invoice_number}\nTotal: Rp ".number_format($invoice->total,0,',','.')." \nJatuh Tempo: {$invoice->due_date->format('d/m/Y')}";
            if ($invoice->client->email)     $this->sendEmail($invoice->client->email, "Invoice {$invoice->invoice_number}", $msg);
            if ($invoice->client->pic_phone) $this->sendWhatsapp($invoice->client->pic_phone, $msg);
        } catch (\Exception $e) {
            Log::error("notifyInvoiceSent error: ".$e->getMessage());
        }
    }

    public function notifyVisitCompleted(\App\Models\Visit $visit, string $pdfPath = null): void
    {
        try {
            $client = $visit->client;
            $techName = $visit->technician ? $visit->technician->name : '-';
            $msg = "Kunjungan Selesai\nKlien: {$client->name}\nTeknisi: {$techName}\nTanggal: {$visit->visit_date->format('d/m/Y')}";
            // include CSAT link if available (visit linked to ticket with csat)
            $csatLink = '';
            if ($visit->ticket && $visit->ticket->csat) {
                $csatLink = url('/csat/'.$visit->ticket->csat->token);
                $msg .= "\n\nMohon berikan penilaian: {$csatLink}";
            }

            if ($client->email) {
                if ($pdfPath && file_exists(storage_path('app/public/'.$pdfPath))) {
                    try {
                        Mail::raw($msg, function ($m) use ($client, $pdfPath) {
                            $m->to($client->email)->subject('Laporan Kunjungan')->attach(storage_path('app/public/'.$pdfPath));
                        });
                    } catch (\Exception $e) {
                        Log::error('Email attachment error: '.$e->getMessage());
                        if ($client->pic_phone) {
                            $this->sendWhatsapp($client->pic_phone, $msg);
                        }
                    }
                } else {
                    $this->sendEmail($client->email, 'Laporan Kunjungan', $msg);
                }
            } elseif ($client->pic_phone) {
                $this->sendWhatsapp($client->pic_phone, $msg);
            }

            $this->notifyUser($visit->technician, $msg, 'Laporan Kunjungan');
        } catch (\Exception $e) {
            Log::error("notifyVisitCompleted error: ".$e->getMessage());
        }
    }
}
