<?php
// app/Http/Resources/Api/Customer/JobApplicationResource.php
namespace App\Http\Resources\Api\Customer;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class JobApplicationResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'job_posting_id' => $this->job_posting_id,
            'job_title' => $this->jobPosting->title ?? 'Unknown',
            'applicant_name' => $this->applicant_name,
            'applicant_email' => $this->applicant_email,
            'applicant_phone' => $this->applicant_phone,
            'cv_filename' => $this->cv_original_name ?? basename($this->applicant_cv),
            'cv_url' => $this->applicant_cv ? url('storage/' . $this->applicant_cv) : null,
            'cover_letter' => $this->cover_letter,
            'status' => $this->status,
            'formatted_status' => $this->getFormattedStatus(),
            'status_badge' => $this->getStatusBadge(),
            'can_withdraw' => $this->canBeWithdrawn(),
            'can_update' => $this->canBeUpdated(),
            'submitted_at' => $this->submitted_at->format('Y-m-d H:i:s'),
            'time_ago' => $this->submitted_at->diffForHumans(),
            'notes' => $this->notes,
            'job' => $this->whenLoaded('jobPosting', function () {
                return [
                    'id' => $this->jobPosting->id,
                    'title' => $this->jobPosting->title,
                    'department' => $this->jobPosting->department,
                    'location' => $this->jobPosting->location,
                    'employment_type' => $this->jobPosting->employment_type,
                ];
            }),
        ];
    }

    private function getFormattedStatus(): string
    {
        $statuses = [
            'pending' => 'Menunggu Review',
            'reviewed' => 'Direview',
            'interviewed' => 'Interview',
            'accepted' => 'Diterima',
            'rejected' => 'Ditolak',
            'withdrawn' => 'Ditarik',
        ];

        return $statuses[$this->status] ?? $this->status;
    }

    private function getStatusBadge(): string
    {
        $badges = [
            'pending' => 'warning',
            'reviewed' => 'info',
            'interviewed' => 'primary',
            'accepted' => 'success',
            'rejected' => 'danger',
            'withdrawn' => 'secondary',
        ];

        return $badges[$this->status] ?? 'secondary';
    }

    private function canBeWithdrawn(): bool
    {
        return in_array($this->status, ['pending', 'reviewed']);
    }

    private function canBeUpdated(): bool
    {
        return $this->status === 'pending' && 
               $this->submitted_at->addHours(24)->isFuture();
    }
}