<?php
// app/Http\Controllers\Api\Customer\CareerController.php
namespace App\Http\Controllers\Api\Customer;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\Customer\JobApplicationRequest;
use App\Http\Requests\Api\Customer\UpdateApplicationRequest;
use App\Http\Resources\Api\Customer\JobPostingResource;
use App\Http\Resources\Api\Customer\JobApplicationResource;
use App\Models\JobPosting;
use App\Models\JobApplication;
use App\Traits\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class CareerController extends Controller
{
    use ApiResponse;

    /**
     * Get active job postings with filters
     * GET /api/customer/careers
     */
    public function index(Request $request): JsonResponse
    {
        $jobs = JobPosting::where('is_active', true)
                        ->where('application_deadline', '>=', now())
                        ->when($request->department, function ($q, $department) {
                            return $q->where('department', 'like', "%{$department}%");
                        })
                        ->when($request->location, function ($q, $location) {
                            return $q->where('location', 'like', "%{$location}%");
                        })
                        ->when($request->employment_type, function ($q, $type) {
                            return $q->where('employment_type', $type);
                        })
                        ->when($request->search, function ($q, $search) {
                            return $q->where(function ($query) use ($search) {
                                $query->where('title', 'like', "%{$search}%")
                                      ->orWhere('description', 'like', "%{$search}%");
                            });
                        })
                        ->orderBy('created_at', 'desc')
                        ->paginate($request->per_page ?? 10);

        // Get filter options
        $departments = JobPosting::where('is_active', true)
                                ->where('application_deadline', '>=', now())
                                ->distinct('department')
                                ->pluck('department');

        $locations = JobPosting::where('is_active', true)
                              ->where('application_deadline', '>=', now())
                              ->distinct('location')
                              ->pluck('location');

        $employmentTypes = [
            ['value' => 'full_time', 'label' => 'Full Time'],
            ['value' => 'part_time', 'label' => 'Part Time'],
            ['value' => 'contract', 'label' => 'Kontrak'],
            ['value' => 'internship', 'label' => 'Magang'],
        ];

        return $this->successResponse([
            'jobs' => JobPostingResource::collection($jobs),
            'pagination' => [
                'total' => $jobs->total(),
                'per_page' => $jobs->perPage(),
                'current_page' => $jobs->currentPage(),
                'last_page' => $jobs->lastPage(),
                'from' => $jobs->firstItem(),
                'to' => $jobs->lastItem(),
            ],
            'filters' => [
                'search' => $request->search,
                'department' => $request->department,
                'location' => $request->location,
                'employment_type' => $request->employment_type,
            ],
            'filter_options' => [
                'departments' => $departments,
                'locations' => $locations,
                'employment_types' => $employmentTypes,
            ],
            'stats' => [
                'total_jobs' => JobPosting::where('is_active', true)
                                         ->where('application_deadline', '>=', now())
                                         ->count(),
                'urgent_jobs' => JobPosting::where('is_active', true)
                                          ->where('application_deadline', '>=', now())
                                          ->where('application_deadline', '<=', now()->addDays(7))
                                          ->count(),
            ]
        ], 'Lowongan kerja berhasil diambil');
    }

    /**
     * Get job detail
     * GET /api/customer/careers/{id}
     */
    public function show(Request $request, $id): JsonResponse
    {
        $job = JobPosting::where('is_active', true)
                       ->where('application_deadline', '>=', now())
                       ->find($id);

        if (!$job) {
            return $this->errorResponse('Lowongan tidak ditemukan atau sudah ditutup', 404);
        }

        // Increment view count
        $job->increment('views_count');

        // Check if user has applied
        $hasApplied = false;
        $userApplication = null;
        
        if ($request->user()) {
            $userApplication = JobApplication::where('job_posting_id', $id)
                                           ->where('applicant_email', $request->user()->email)
                                           ->first();
            $hasApplied = (bool) $userApplication;
        }

        $response = new JobPostingResource($job);
        $responseData = $response->toArray($request);
        $responseData['has_applied'] = $hasApplied;
        $responseData['application_status'] = $userApplication ? $userApplication->status : null;
        $responseData['application_id'] = $userApplication ? $userApplication->id : null;

        return $this->successResponse(
            $responseData,
            'Detail lowongan berhasil diambil'
        );
    }

    /**
     * Apply for job
     * POST /api/customer/careers/{id}/apply
     */
    public function apply(JobApplicationRequest $request, $id): JsonResponse
    {
        DB::beginTransaction();
        
        try {
            $validated = $request->validated();
            $user = $request->user();

            // Cek job posting
            $job = JobPosting::where('is_active', true)
                           ->where('application_deadline', '>=', now())
                           ->find($id);

            if (!$job) {
                return $this->errorResponse('Lowongan tidak ditemukan atau sudah ditutup', 404);
            }

            // Cek apakah sudah pernah apply
            $existing = JobApplication::where('job_posting_id', $id)
                                    ->where('applicant_email', $validated['email'])
                                    ->first();

            if ($existing) {
                return $this->successResponse(
                    new JobApplicationResource($existing->load('jobPosting')),
                    'Anda sudah melamar lowongan ini. Status: ' . $existing->getFormattedStatus()
                );
            }

            // Upload CV
            $cvPath = null;
            $cvOriginalName = null;
            
            if ($request->hasFile('cv')) {
                $file = $request->file('cv');
                $cvOriginalName = $file->getClientOriginalName();
                
                // Validasi file type
                $allowedExtensions = ['pdf', 'doc', 'docx'];
                $extension = $file->getClientOriginalExtension();
                
                if (!in_array(strtolower($extension), $allowedExtensions)) {
                    return $this->errorResponse(
                        'Format CV tidak didukung. Gunakan PDF, DOC, atau DOCX',
                        400
                    );
                }

                // Validasi file size (max 5MB)
                if ($file->getSize() > 5 * 1024 * 1024) {
                    return $this->errorResponse('Ukuran CV maksimal 5MB', 400);
                }

                // Generate unique filename
                $fileName = 'cv_' . time() . '_' . uniqid() . '.' . $extension;
                $path = $file->storeAs('job-applications/cv', $fileName, 'public');
                $cvPath = $path;
            }

            // Buat aplikasi
            $application = JobApplication::create([
                'job_posting_id' => $job->id,
                'applicant_name' => $validated['name'],
                'applicant_email' => $validated['email'],
                'applicant_phone' => $validated['phone'],
                'applicant_cv' => $cvPath,
                'cv_original_name' => $cvOriginalName,
                'cover_letter' => $validated['cover_letter'] ?? null,
                'submitted_at' => now(),
                'status' => 'pending',
                'notes' => 'Applied via customer portal',
            ]);

            // Update application count for job
            $job->increment('application_count');

            DB::commit();

            return $this->successResponse(
                new JobApplicationResource($application->load('jobPosting')),
                '🎉 Lamaran berhasil dikirim! Kami akan menghubungi Anda via email/telepon.',
                201
            );

        } catch (\Exception $e) {
            DB::rollBack();
            return $this->errorResponse('Gagal mengirim lamaran: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Get my applications
     * GET /api/customer/careers/applications/my
     */
    public function myApplications(Request $request): JsonResponse
    {
        $user = $request->user();
        
        $applications = JobApplication::where('applicant_email', $user->email)
                                    ->with(['jobPosting'])
                                    ->when($request->status, function ($q, $status) {
                                        return $q->where('status', $status);
                                    })
                                    ->when($request->date_from && $request->date_to, function ($q) use ($request) {
                                        return $q->whereBetween('submitted_at', [
                                            $request->date_from . ' 00:00:00',
                                            $request->date_to . ' 23:59:59'
                                        ]);
                                    })
                                    ->orderBy('created_at', 'desc')
                                    ->paginate($request->per_page ?? 10);

        // Application statistics
        $stats = [
            'total' => JobApplication::where('applicant_email', $user->email)->count(),
            'pending' => JobApplication::where('applicant_email', $user->email)
                                     ->where('status', 'pending')->count(),
            'reviewed' => JobApplication::where('applicant_email', $user->email)
                                       ->where('status', 'reviewed')->count(),
            'interviewed' => JobApplication::where('applicant_email', $user->email)
                                          ->where('status', 'interviewed')->count(),
            'accepted' => JobApplication::where('applicant_email', $user->email)
                                       ->where('status', 'accepted')->count(),
            'rejected' => JobApplication::where('applicant_email', $user->email)
                                       ->where('status', 'rejected')->count(),
        ];

        return $this->successResponse([
            'applications' => JobApplicationResource::collection($applications),
            'pagination' => [
                'total' => $applications->total(),
                'per_page' => $applications->perPage(),
                'current_page' => $applications->currentPage(),
                'last_page' => $applications->lastPage(),
                'from' => $applications->firstItem(),
                'to' => $applications->lastItem(),
            ],
            'statistics' => $stats,
            'filters' => [
                'status' => $request->status,
                'date_from' => $request->date_from,
                'date_to' => $request->date_to,
            ]
        ], 'Lamaran Anda berhasil diambil');
    }

    /**
     * Get application detail
     * GET /api/customer/careers/applications/{id}
     */
    public function getApplication(Request $request, $id): JsonResponse
    {
        $user = $request->user();
        
        $application = JobApplication::with(['jobPosting'])
                                    ->where('applicant_email', $user->email)
                                    ->find($id);

        if (!$application) {
            return $this->errorResponse('Lamaran tidak ditemukan', 404);
        }

        return $this->successResponse(
            new JobApplicationResource($application),
            'Detail lamaran berhasil diambil'
        );
    }

    /**
     * Update application (cover letter, etc.)
     * PUT /api/customer/careers/applications/{id}
     */
    public function updateApplication(UpdateApplicationRequest $request, $id): JsonResponse
    {
        DB::beginTransaction();
        
        try {
            $user = $request->user();
            
            $application = JobApplication::where('applicant_email', $user->email)
                                       ->where('status', 'pending') // Only pending can be updated
                                       ->find($id);

            if (!$application) {
                return $this->errorResponse('Lamaran tidak dapat diupdate', 404);
            }

            // Check if still within editable period (24 hours)
            if ($application->submitted_at->addHours(24)->isPast()) {
                return $this->errorResponse('Lamaran hanya dapat diupdate dalam 24 jam pertama', 400);
            }

            $validated = $request->validated();

            // Handle CV update if provided
            if ($request->hasFile('cv')) {
                // Delete old CV if exists
                if ($application->applicant_cv && Storage::exists('public/' . $application->applicant_cv)) {
                    Storage::delete('public/' . $application->applicant_cv);
                }

                $file = $request->file('cv');
                $cvOriginalName = $file->getClientOriginalName();
                
                // Validasi file type
                $allowedExtensions = ['pdf', 'doc', 'docx'];
                $extension = $file->getClientOriginalExtension();
                
                if (!in_array(strtolower($extension), $allowedExtensions)) {
                    return $this->errorResponse(
                        'Format CV tidak didukung. Gunakan PDF, DOC, atau DOCX',
                        400
                    );
                }

                // Generate unique filename
                $fileName = 'cv_' . time() . '_' . uniqid() . '.' . $extension;
                $path = $file->storeAs('job-applications/cv', $fileName, 'public');
                
                $application->applicant_cv = $path;
                $application->cv_original_name = $cvOriginalName;
            }

            // Update other fields
            $application->update([
                'cover_letter' => $validated['cover_letter'] ?? $application->cover_letter,
                'notes' => $application->notes . "\n[Diupdate: " . now()->format('Y-m-d H:i:s') . "]",
            ]);

            DB::commit();

            return $this->successResponse(
                new JobApplicationResource($application->fresh(['jobPosting'])),
                '✅ Lamaran berhasil diperbarui'
            );

        } catch (\Exception $e) {
            DB::rollBack();
            return $this->errorResponse('Gagal memperbarui lamaran: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Withdraw application
     * DELETE /api/customer/careers/applications/{id}
     */
    public function withdrawApplication(Request $request, $id): JsonResponse
    {
        DB::beginTransaction();
        
        try {
            $user = $request->user();
            
            $application = JobApplication::where('applicant_email', $user->email)
                                       ->whereIn('status', ['pending', 'reviewed']) // Only these can be withdrawn
                                       ->find($id);

            if (!$application) {
                return $this->errorResponse('Lamaran tidak dapat ditarik', 404);
            }

            // Delete CV file
            if ($application->applicant_cv && Storage::exists('public/' . $application->applicant_cv)) {
                Storage::delete('public/' . $application->applicant_cv);
            }

            // Update status to withdrawn
            $application->update([
                'status' => 'withdrawn',
                'notes' => $application->notes . "\n[Ditarik oleh pelamar: " . now()->format('Y-m-d H:i:s') . "]",
            ]);

            // Decrement application count for job
            $application->jobPosting()->decrement('application_count');

            DB::commit();

            return $this->successResponse(
                null,
                '🗑️ Lamaran berhasil ditarik'
            );

        } catch (\Exception $e) {
            DB::rollBack();
            return $this->errorResponse('Gagal menarik lamaran: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Get application status timeline
     * GET /api/customer/careers/applications/{id}/timeline
     */
    public function getApplicationTimeline(Request $request, $id): JsonResponse
    {
        $user = $request->user();
        
        $application = JobApplication::where('applicant_email', $user->email)
                                   ->find($id);

        if (!$application) {
            return $this->errorResponse('Lamaran tidak ditemukan', 404);
        }

        $timeline = $this->generateTimeline($application);

        return $this->successResponse([
            'application_id' => $application->id,
            'job_title' => $application->jobPosting->title ?? 'Unknown',
            'status' => $application->status,
            'formatted_status' => $application->getFormattedStatus(),
            'timeline' => $timeline,
            'next_steps' => $this->getNextSteps($application),
        ], 'Timeline lamaran berhasil diambil');
    }

    /**
     * Get urgent jobs (closing soon)
     * GET /api/customer/careers/urgent
     */
    public function urgentJobs(Request $request): JsonResponse
    {
        $urgentJobs = JobPosting::where('is_active', true)
                               ->where('application_deadline', '>=', now())
                               ->where('application_deadline', '<=', now()->addDays(7))
                               ->orderBy('application_deadline', 'asc')
                               ->limit(5)
                               ->get();

        return $this->successResponse([
            'urgent_jobs' => JobPostingResource::collection($urgentJobs),
            'count' => $urgentJobs->count(),
            'message' => $urgentJobs->count() > 0 
                ? 'Ada ' . $urgentJobs->count() . ' lowongan yang segera ditutup'
                : 'Tidak ada lowongan mendesak',
        ], 'Lowongan mendesak berhasil diambil');
    }

    /**
     * Get career statistics
     * GET /api/customer/careers/stats
     */
    public function careerStats(Request $request): JsonResponse
    {
        $user = $request->user();

        $totalApplications = JobApplication::where('applicant_email', $user->email)->count();
        $activeApplications = JobApplication::where('applicant_email', $user->email)
                                          ->whereIn('status', ['pending', 'reviewed', 'interviewed'])
                                          ->count();

        $averageResponseTime = JobApplication::where('applicant_email', $user->email)
                                           ->whereNotNull('updated_at')
                                           ->avg(DB::raw('TIMESTAMPDIFF(DAY, submitted_at, updated_at)'));

        $successRate = $totalApplications > 0 
            ? round((JobApplication::where('applicant_email', $user->email)
                                 ->where('status', 'accepted')
                                 ->count() / $totalApplications) * 100, 1)
            : 0;

        return $this->successResponse([
            'statistics' => [
                'total_applications' => $totalApplications,
                'active_applications' => $activeApplications,
                'average_response_days' => round($averageResponseTime ?? 0, 1),
                'success_rate_percent' => $successRate,
                'application_status_distribution' => [
                    'pending' => JobApplication::where('applicant_email', $user->email)
                                             ->where('status', 'pending')->count(),
                    'reviewed' => JobApplication::where('applicant_email', $user->email)
                                               ->where('status', 'reviewed')->count(),
                    'interviewed' => JobApplication::where('applicant_email', $user->email)
                                                  ->where('status', 'interviewed')->count(),
                    'accepted' => JobApplication::where('applicant_email', $user->email)
                                               ->where('status', 'accepted')->count(),
                    'rejected' => JobApplication::where('applicant_email', $user->email)
                                               ->where('status', 'rejected')->count(),
                ],
            ],
            'achievements' => $this->getCareerAchievements($user->email),
        ], 'Statistik karir berhasil diambil');
    }

    // ==================== HELPER METHODS ====================

    /**
     * Generate timeline for application
     */
    private function generateTimeline(JobApplication $application): array
    {
        $timeline = [];

        // Submitted
        $timeline[] = [
            'status' => 'submitted',
            'title' => 'Lamaran Dikirim',
            'description' => 'Lamaran berhasil dikirim',
            'time' => $application->submitted_at->format('Y-m-d H:i:s'),
            'icon' => '📤',
            'completed' => true,
        ];

        // If reviewed
        if (in_array($application->status, ['reviewed', 'interviewed', 'accepted', 'rejected'])) {
            $timeline[] = [
                'status' => 'reviewed',
                'title' => 'Dalam Review',
                'description' => 'Lamaran sedang direview HRD',
                'time' => $application->updated_at->format('Y-m-d H:i:s'),
                'icon' => '📋',
                'completed' => true,
            ];
        }

        // If interviewed
        if (in_array($application->status, ['interviewed', 'accepted', 'rejected'])) {
            $timeline[] = [
                'status' => 'interviewed',
                'title' => 'Interview',
                'description' => 'Menunggu jadwal interview',
                'time' => $application->updated_at->format('Y-m-d H:i:s'),
                'icon' => '💼',
                'completed' => true,
            ];
        }

        // Current status
        $statusIcons = [
            'pending' => ['icon' => '⏳', 'title' => 'Menunggu Review'],
            'reviewed' => ['icon' => '👁️', 'title' => 'Sedang Direview'],
            'interviewed' => ['icon' => '🗣️', 'title' => 'Interview'],
            'accepted' => ['icon' => '✅', 'title' => 'Diterima'],
            'rejected' => ['icon' => '❌', 'title' => 'Ditolak'],
            'withdrawn' => ['icon' => '↩️', 'title' => 'Ditarik'],
        ];

        if (isset($statusIcons[$application->status])) {
            $timeline[] = [
                'status' => $application->status,
                'title' => $statusIcons[$application->status]['title'],
                'description' => 'Status saat ini',
                'time' => 'Sekarang',
                'icon' => $statusIcons[$application->status]['icon'],
                'completed' => in_array($application->status, ['accepted', 'rejected', 'withdrawn']),
                'current' => !in_array($application->status, ['accepted', 'rejected', 'withdrawn']),
            ];
        }

        return $timeline;
    }

    /**
     * Get next steps for application
     */
    private function getNextSteps(JobApplication $application): array
    {
        $steps = [];

        if ($application->status === 'pending') {
            $steps[] = [
                'action' => 'wait',
                'description' => 'Tunggu konfirmasi dari HRD (3-7 hari kerja)',
                'icon' => '⏳',
            ];
            $steps[] = [
                'action' => 'prepare',
                'description' => 'Persiapkan dokumen pendukung',
                'icon' => '📄',
            ];
        }

        if ($application->status === 'reviewed') {
            $steps[] = [
                'action' => 'wait_interview',
                'description' => 'Tunggu jadwal interview dari HRD',
                'icon' => '🗓️',
            ];
            $steps[] = [
                'action' => 'research',
                'description' => 'Pelajari tentang perusahaan dan posisi',
                'icon' => '🔍',
            ];
        }

        if ($application->status === 'interviewed') {
            $steps[] = [
                'action' => 'wait_decision',
                'description' => 'Tunggu keputusan final',
                'icon' => '⚖️',
            ];
            $steps[] = [
                'action' => 'follow_up',
                'description' => 'Kirim email follow-up jika perlu',
                'icon' => '📧',
            ];
        }

        if ($application->status === 'accepted') {
            $steps[] = [
                'action' => 'confirm',
                'description' => 'Konfirmasi penerimaan tawaran',
                'icon' => '✅',
            ];
            $steps[] = [
                'action' => 'prepare_start',
                'description' => 'Persiapkan diri untuk hari pertama kerja',
                'icon' => '🚀',
            ];
        }

        return $steps;
    }

    /**
     * Get career achievements
     */
    private function getCareerAchievements(string $email): array
    {
        $achievements = [];

        $totalApplications = JobApplication::where('applicant_email', $email)->count();
        $acceptedCount = JobApplication::where('applicant_email', $email)
                                     ->where('status', 'accepted')
                                     ->count();

        // First application
        if ($totalApplications >= 1) {
            $achievements[] = [
                'name' => 'Pemula',
                'description' => 'Kirim lamaran pertama',
                'icon' => '🥇',
                'unlocked' => true,
                'progress' => 100,
            ];
        }

        // Multiple applications
        if ($totalApplications >= 5) {
            $achievements[] = [
                'name' => 'Pencari Aktif',
                'description' => 'Kirim 5 lamaran',
                'icon' => '📈',
                'unlocked' => true,
                'progress' => 100,
            ];
        } elseif ($totalApplications > 0) {
            $achievements[] = [
                'name' => 'Pencari Aktif',
                'description' => 'Kirim 5 lamaran',
                'icon' => '📈',
                'unlocked' => false,
                'progress' => ($totalApplications / 5) * 100,
            ];
        }

        // Successful application
        if ($acceptedCount >= 1) {
            $achievements[] = [
                'name' => 'Diterima!',
                'description' => 'Lamaran diterima',
                'icon' => '🏆',
                'unlocked' => true,
                'progress' => 100,
            ];
        }

        return $achievements;
    }

    /**
     * Get application tips
     * GET /api/customer/careers/tips
     */
    public function getApplicationTips(Request $request): JsonResponse
    {
        $tips = [
            [
                'title' => 'CV yang Menarik',
                'description' => 'Pastikan CV Anda singkat, jelas, dan relevan dengan posisi',
                'icon' => '📄',
                'details' => [
                    'Maksimal 2 halaman',
                    'Sertakan pengalaman relevan',
                    'Gunakan format PDF',
                ]
            ],
            [
                'title' => 'Cover Letter yang Personal',
                'description' => 'Tulis cover letter yang spesifik untuk setiap lamaran',
                'icon' => '✍️',
                'details' => [
                    'Sebutkan nama perusahaan',
                    'Jelaskan mengapa Anda cocok',
                    'Sertakan kontak yang mudah dihubungi',
                ]
            ],
            [
                'title' => 'Persiapan Interview',
                'description' => 'Persiapkan diri dengan baik untuk interview',
                'icon' => '💼',
                'details' => [
                    'Pelajari profil perusahaan',
                    'Siapkan pertanyaan untuk interviewer',
                    'Berpakaian rapi dan sopan',
                ]
            ],
        ];

        return $this->successResponse([
            'tips' => $tips,
            'contact' => [
                'email' => 'hrd@chingubite.com',
                'phone' => '0812-3456-7890',
                'office_hours' => 'Senin - Jumat, 09:00 - 17:00',
            ]
        ], 'Tips lamaran kerja berhasil diambil');
    }
}