<?php

namespace App\Notifications;

use App\Models\EmployeeUndertime;
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 Undertime extends Notification
{
    use Queueable;

    private string $message;

    /**
     * Create a new notification instance.
     */
    public function __construct(private EmployeeUndertime $undertime)
    {
        $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('Undertime Notification - AUTOHUB GROUP')
            ->view('emails.undertime', [
                'notifiable' => $notifiable,
                'undertime' => $this->undertime,
                '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->undertime->attachment)
            ]);
        
        // Attach the file if it exists
        if ($this->undertime->attachment) {
            $attachmentPath = storage_path('app/employee-undertime/' . $this->undertime->attachment);
            if (file_exists($attachmentPath)) {
                $mail->attach($attachmentPath, [
                    'as' => $this->undertime->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.undertime.public.approve',
            $expiration,
            ['undertime' => $this->undertime->id, 'approver' => $notifiable->id]
        );
        
        $denyApiUrl = URL::temporarySignedRoute(
            'api.undertime.public.deny',
            $expiration,
            ['undertime' => $this->undertime->id, 'approver' => $notifiable->id]
        );
        
        $viewApiUrl = URL::temporarySignedRoute(
            'api.undertime.public.view',
            $expiration,
            ['undertime' => $this->undertime->id, 'viewer' => $notifiable->id]
        );

        // Return frontend URLs with encoded API URLs as parameters
        return [
            'approve' => $frontendUrl . '/undertime-action?token=' . base64_encode($approveApiUrl) . '&action=approve',
            'deny' => $frontendUrl . '/undertime-action?token=' . base64_encode($denyApiUrl) . '&action=deny',
            'view' => $frontendUrl . '/undertime-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->undertime->status == 0 || $this->undertime->status == 1) && 
               $this->undertime->employee_id != $notifiable->id;
    }

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

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

    /**
     * Get readable status text
     */
    private function getStatusText(): string
    {
        if ($this->undertime->validated == 1) {
            return 'Validated by HR';
        } elseif ($this->undertime->validated == 99) {
            return 'Denied by HR';
        } elseif ($this->undertime->status == 2) {
            return 'Approved';
        } elseif ($this->undertime->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->undertime->validated == 1){
            $title = "Your undertime application has been received and validated by HR";
        }else if($this->undertime->validated == 99){
            $title = "Your undertime application has been denied by HR";
        }else if($this->undertime->status == 2){
           $title =  "Your undertime application has been approved";
        }else if($this->undertime->status == 99){
            $title = "Your undertime application has been denied";
        }else{
            $title = $this->undertime->employee->firstname . ' ' . $this->undertime->employee->lastname." Submitted Undertime Application";
            $isApprover = true;
        } 

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

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

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