<?php

namespace App\Notifications;

use App\Models\EmployeeOb;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\URL;

class Travel extends Notification
{
    use Queueable;

    private string $message;

    /**
     * Create a new notification instance.
     */
    public function __construct(private EmployeeOb $ob)
    {
        $this->message = $this->generateMessage();
    }

    /**
     * Get the notification's delivery channels.
     *
     * @return array<int, string>
     */
    public function via(object $notifiable): array
    {
        return ['mail', 'database'];
    }

    /**
     * Get the mail representation of the notification.
     */
    public function toMail(object $notifiable): MailMessage
    {
        $frontendUrl = config('app.frontend_url');
        $urls = $this->generateActionUrls($notifiable, $frontendUrl);
        
        $mail = (new MailMessage)
            ->subject('OB/Travel Notification - AUTOHUB GROUP')
            ->view('emails.travel', [
                'notifiable' => $notifiable,
                'ob' => $this->ob,
                'msg' => $this->message,
                'statusBadge' => $this->getStatusBadge(),
                'statusColor' => $this->getStatusColor(),
                'statusText' => $this->getStatusText(),
                'approveUrl' => $urls['approve'],
                'denyUrl' => $urls['deny'],
                'viewUrl' => $urls['view'],
                'showActionButtons' => $this->shouldShowActionButtons($notifiable),
                'hasAttachment' => !empty($this->ob->attachment)
            ]);
        
        // Attach the file if it exists
        if ($this->ob->attachment) {
            $attachmentPath = storage_path('app/employee-ob/' . $this->ob->attachment);
            if (file_exists($attachmentPath)) {
                $mail->attach($attachmentPath, [
                    'as' => $this->ob->attachment,
                    'mime' => mime_content_type($attachmentPath)
                ]);
            }
        }
        
        return $mail;
    }

    /**
     * Generate frontend URLs that will handle the signed API calls
     */
    private function generateActionUrls($notifiable, $frontendUrl): array
    {
        $expiration = now()->addDays(7);
        
        // Generate signed API URLs
        $approveApiUrl = URL::temporarySignedRoute(
            'api.ob.public.approve',
            $expiration,
            ['ob' => $this->ob->id, 'approver' => $notifiable->id]
        );
        
        $denyApiUrl = URL::temporarySignedRoute(
            'api.ob.public.deny',
            $expiration,
            ['ob' => $this->ob->id, 'approver' => $notifiable->id]
        );
        
        $viewApiUrl = URL::temporarySignedRoute(
            'api.ob.public.view',
            $expiration,
            ['ob' => $this->ob->id, 'viewer' => $notifiable->id]
        );

        // Return frontend URLs with encoded API URLs as parameters
        return [
            'approve' => $frontendUrl . '/ob-action?token=' . base64_encode($approveApiUrl) . '&action=approve',
            'deny' => $frontendUrl . '/ob-action?token=' . base64_encode($denyApiUrl) . '&action=deny',
            'view' => $frontendUrl . '/ob-action?token=' . base64_encode($viewApiUrl) . '&action=view',
        ];
    }

    /**
     * Determine if action buttons should be shown
     */
    private function shouldShowActionButtons($notifiable): bool
    {
        // Show buttons only for pending applications and if user is not the applicant
        return ($this->ob->status == 0 || $this->ob->status == 1) && 
               $this->ob->employee_id != $notifiable->id;
    }

    /**
     * Get status badge text
     */
    private function getStatusBadge(): string
    {
        if ($this->ob->validated == 1) {
            return 'HR Validated';
        } elseif ($this->ob->validated == 99) {
            return 'HR Denied';
        } elseif ($this->ob->status == 2) {
            return 'Approved';
        } elseif ($this->ob->status == 99) {
            return 'Denied';
        } else {
            return 'Pending Review';
        }
    }

    /**
     * Get status color
     */
    private function getStatusColor(): string
    {
        if ($this->ob->validated == 1 || $this->ob->status == 2) {
            return '#28a745'; // Green for approved/validated
        } elseif ($this->ob->validated == 99 || $this->ob->status == 99) {
            return '#dc3545'; // Red for denied
        } else {
            return '#ffc107'; // Yellow for pending
        }
    }

    /**
     * Get readable status text
     */
    private function getStatusText(): string
    {
        if ($this->ob->validated == 1) {
            return 'Validated by HR';
        } elseif ($this->ob->validated == 99) {
            return 'Denied by HR';
        } elseif ($this->ob->status == 2) {
            return 'Approved';
        } elseif ($this->ob->status == 99) {
            return 'Denied';
        } else {
            return 'Pending Review';
        }
    }

    /**
     * Get the array representation of the notification.
     *
     * @return array<string, mixed>
     */
    public function toArray(object $notifiable): array
    {
        $title = null;
        $isApprover = false;

        if($this->ob->validated == 1){
            $title = "Your OB application has been received and validated by HR";
        }else if($this->ob->validated == 99){
            $title = "Your OB application has been denied by HR";
        }else if($this->ob->status == 2){
           $title =  "Your OB application has been approved";
        }else if($this->ob->status == 99){
            $title = "Your OB application has been denied";
        }else{
            $title = $this->ob->employee->firstname . ' ' . $this->ob->employee->lastname." Submitted OB Application";
            $isApprover = true;
        } 

        return [
            'ob_id' => $this->ob->id,
            'status' => $this->ob->status,
            'approved_at' => $this->ob->approved_at,
            'message' => $this->message,
            'title' => $title,
            'url' => $isApprover ? 'attendance/ob-action' : 'attendance/official-business',
            'created_by' => $this->ob->employee_id
        ];
    }

    /**
     * Generate the message based on ob status.
     */
    private function generateMessage(): string
    {
        $fullname = $this->ob->employee->firstname.' '.$this->ob->employee->lastname;
        $date = $this->ob->date_from;
        $from_time = $this->ob->from_time;
        $to_time = $this->ob->to_time;
        $created_at = Carbon::parse($this->ob->created_at)->setTimezone('Asia/Shanghai');

        switch ($this->ob->status) {
            case 1:
            case 0:
                return "$fullname filed OB application dated \"$date\" time from \"$from_time\" to \"$to_time\" for your validation.";
            case 2:
                if($this->ob->validated == 1){
                    return "Your OB application dated \"$date\" time from \"$from_time\" to \"$to_time\" has been received and validated by HR.";
                }else if($this->ob->validated == 99){
                    return "Your OB application dated \"$date\" time from \"$from_time\" to \"$to_time\" has been denied by HR.";
                }else{
                    return "Your OB application dated \"$date\" time from \"$from_time\" to \"$to_time\" has been approved.";
                }
                
            case 99:
                return "Your OB application dated \"$date\" time from \"$from_time\" to \"$to_time\" has been denied.";
            default:
                return 'Unknown status.';
        }
    }
}