<?php

namespace App\Services;

use App\Models\Agent;
use App\Models\Candidate;
use App\Models\RecruitmentCase;
use App\Models\Step;
use App\Models\User;

class WhatsAppTemplateService
{
    private function publicBaseUrl(): string
    {
        $url = (string) config('app.public_url', config('app.url'));
        $url = trim($url);

        // Never send local/development URLs in WhatsApp notifications.
        if ($url === '' || preg_match('/(localhost|127\.0\.0\.1|0\.0\.0\.0)/i', $url)) {
            $url = 'https://nurtravelworld.com';
        }

        return rtrim($url, '/');
    }

    private function loginUrl(): string
    {
        return $this->publicBaseUrl() . '/login';
    }

    private function trackingUrl(?Candidate $candidate): string
    {
        if (! $candidate || empty($candidate->public_track_token)) {
            return $this->publicBaseUrl() . '/track';
        }

        return $this->publicBaseUrl() . '/t/' . $candidate->public_track_token;
    }

    public function agentAccountCreatedMessage(Agent $agent, User $user, string $plainPassword): string
    {
        $name = $agent->name ?: $user->name;
        $email = $user->email;

        return "👋 *Welcome to Nur Travel World*\n\n"
            . "Dear {$name},\nYour *Agent account* has been created.\n\n"
            . "Login Email: {$email}\n"
            . "Password: {$plainPassword}\n\n"
            . "Login URL: " . $this->loginUrl() . "\n\n"
            . "Please change your password after first login.";
    }

    public function adminAgentAccountCreatedMessage(Agent $agent, User $user, string $createdBy = ''): string
    {
        $by = $createdBy ? "\nCreated By: {$createdBy}" : '';
        return "🆕 *New Agent Created*\n\n"
            . "Name: {$agent->name}\n"
            . "Phone: " . ($agent->phone ?? '') . "\n"
            . "Email: {$user->email}"
            . $by;
    }

    public function candidateAccountCreatedMessage(Candidate $candidate): string
    {
        $name = $candidate->full_name ?? 'Candidate';
        $country = $candidate->destination_country ?? '';
        $passport = $candidate->passport_no ?? '';

        return "🌍 *Nur Travel World*\n\n"
            . "Hello {$name},\n"
            . "Your file has been opened with us for {$country}.\n\n"
            . "Passport: {$passport}\n"
            . "We will update you step-by-step on WhatsApp.\n"
            . "Track URL: " . $this->trackingUrl($candidate) . "\n\n"
            . "If you need urgent help, reply to this message.";
    }

    public function adminCandidateAccountCreatedMessage(Candidate $candidate, string $agentName = '', string $createdBy = ''): string
    {
        $by = $createdBy ? "\nCreated By: {$createdBy}" : '';
        $agentLine = $agentName ? "\nAgent: {$agentName}" : '';
        return "🆕 *New Candidate Created*\n\n"
            . "Name: {$candidate->full_name}\n"
            . "Phone: " . ($candidate->phone ?? '') . "\n"
            . "Passport: {$candidate->passport_no}\n"
            . "Country: " . ($candidate->destination_country ?? '')
            . $agentLine
            . $by;
    }

    public function agentCandidateAccountCreatedMessage(Candidate $candidate, string $createdBy = ''): string
    {
        $by = $createdBy ? "\nCreated By: {$createdBy}" : '';
        return "📣 *New Candidate Assigned*\n\n"
            . "Name: {$candidate->full_name}\n"
            . "Phone: " . ($candidate->phone ?? '') . "\n"
            . "Passport: {$candidate->passport_no}\n"
            . "Country: " . ($candidate->destination_country ?? '')
            . $by
            . "\n\nPlease contact the candidate and guide them for the next steps.";
    }

    public function candidateStepMessage(RecruitmentCase $case, Step $newStep): string
    {
        $candidate = $case->candidate;
        $name = $candidate?->full_name ?? 'Candidate';
        $country = $candidate?->destination_country ?? '';
        $passport = $candidate?->passport_no ?? '';
        $ref = $passport ?: ('CASE-' . $case->id);

        $step = $newStep->name;

        $header = "🌍 *Nur Travel World*\n\n";
        $footer = "\n\nReference: {$ref}" . "\nTrack URL: " . $this->trackingUrl($candidate);

        $msg = match ($step) {
            'Passport Collected' => "📘 *Passport Collected*\n\nDear {$name},\nWe have successfully collected your passport for the {$country} process.\nNext step: Medical.",
            'Medical' => "🩺 *Medical Update*\n\nDear {$name},\nYour medical step has been updated. We will inform you about the next step soon.",
            'Biometric' => "🖐 *Biometric Update*\n\nDear {$name},\nYour biometric step has been updated. Next step: BMET/MOFA processing.",
            'BMET/MOFA' => "🏛 *BMET / MOFA Update*\n\nDear {$name},\nYour BMET/MOFA processing has been updated successfully.",
            'Sent to India' => "✈️ *File Sent to India*\n\nDear {$name},\nYour visa file has been sent to India for further processing.",
            'Submitted to Embassy' => "🏢 *Submitted to Embassy*\n\nDear {$name},\nYour application has been submitted to the Embassy. Please wait for the response.",
            'Visa Application Submitted' => "📄 *Visa Application Submitted*\n\nDear {$name},\nYour visa application has been submitted successfully.",
            'Visa In Process' => "⏳ *Visa In Process*\n\nDear {$name},\nYour visa is now under process. Processing time may vary.",
            'Visa Approved' => "🎉 *Visa Approved*\n\nCongratulations {$name}!\nYour visa has been approved successfully. Next step: Visa stamping.",
            'Visa Refused' => "⚠️ *Visa Refused*\n\nDear {$name},\nWe regret to inform you that your visa has been refused. Please contact us for guidance.",
            'Visa Stamping' => "🛂 *Visa Stamping Update*\n\nDear {$name},\nYour visa stamping step has been updated. Next step: Ticket processing.",
            'Ticket' => "🎟 *Ticket Update*\n\nDear {$name},\nYour ticket step has been updated. We will share flight details shortly.",
            'Ready to Fly' => "✈️ *Ready to Fly*\n\nDear {$name},\nAll processing steps are completed. You are ready to fly. Please prepare your documents.",
            'Departed' => "🌍 *Departure Confirmed*\n\nDear {$name},\nDeparture has been confirmed. We wish you a safe and successful journey!",
            'Passport Received' => "📦 *Passport Received*\n\nDear {$name},\nYour passport has been received back. Please visit our office to collect it.",
            default => "🔔 *Step Update*\n\nDear {$name},\nYour application status has been updated to: *{$step}*.",
        };

        return $header . $msg . $footer;
    }

    public function adminStepMessage(RecruitmentCase $case, ?Step $oldStep, Step $newStep, string $updatedBy = ''): string
    {
        $candidate = $case->candidate;
        $name = $candidate?->full_name ?? '';
        $phone = $candidate?->phone ?? '';
        $country = $candidate?->destination_country ?? '';
        $passport = $candidate?->passport_no ?? '';
        $ref = $passport ?: ('CASE-' . $case->id);

        $old = $oldStep?->name ?? '(none)';
        $new = $newStep->name;

        $updatedByLine = $updatedBy ? "\nUpdated By: {$updatedBy}" : '';

        return "🔔 *Candidate Step Updated*\n\n"
            . "Name: {$name}\n"
            . "Phone: {$phone}\n"
            . "Country: {$country}\n"
            . "Ref: {$ref}\n\n"
            . "Step Changed:\n{$old} ➜ {$new}"
            . $updatedByLine;
    }

    public function agentStepMessage(RecruitmentCase $case, ?Step $oldStep, Step $newStep, string $updatedBy = ''): string
    {
        $candidate = $case->candidate;
        $name = $candidate?->full_name ?? 'Candidate';
        $phone = (string) ($candidate?->phone ?? '');
        $country = $candidate?->destination_country ?? '';
        $passport = $candidate?->passport_no ?? '';
        $ref = $passport ?: ('CASE-' . $case->id);

        $old = $oldStep?->name ?? '(none)';
        $new = $newStep->name;

        $updatedByLine = $updatedBy ? "\nUpdated By: {$updatedBy}" : '';

        return "📣 *Agent Notification: Step Updated*\n\n"
            . "Candidate: {$name}\n"
            . "Phone: {$phone}\n"
            . "Country: {$country}\n"
            . "Ref: {$ref}\n\n"
            . "Step Changed:\n{$old} ➜ {$new}"
            . $updatedByLine
            . "\n\nPlease contact the candidate if any action is needed.";
    }

}
