<?php

namespace App\Notifications;

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

    private string $message;

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

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

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

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

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

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

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

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