<?php

namespace App\Modules\Careers\Http\Controllers;

use App\Modules\Careers\Exports\ApplicationsExport;
use App\Http\Controllers\Controller;
use App\Modules\Careers\Models\Application;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Facades\DataTables;
use Maatwebsite\Excel\Facades\Excel;

class ApplicationController extends Controller
{
    /**
     * Display a listing of the applications.
     */
  public function index(Request $request)
    {
        if ($request->ajax()) {

            $query = Application::query()->latest();

            if ($request->filled('job_title')) {
                $query->where('job_title', $request->job_title);
            }

            if ($request->filled('highest_education')) {
                $query->where('highest_education', $request->highest_education);
            }

            if ($request->filled('experience_years')) {
                $query->where('experience_years', $request->experience_years);
            }

            if ($request->filled('gender')) {
                $query->where('gender', $request->gender);
            }

            if ($request->filled('age')) {
                $query->where('age', $request->age);
            }

            if ($request->filled('date_from') && $request->filled('date_to')) {
                $query->whereBetween('created_at', [
                    $request->date_from,
                    $request->date_to
                ]);
            }

            return DataTables::of($query)
                ->addIndexColumn()

                ->editColumn('experience_years', fn($row) =>
                    $row->experience_years ? $row->experience_years.' yrs' : '-'
                )

                ->editColumn('score', fn($row) =>
                    $row->score
                    ? '<span class="badge bg-primary">'.$row->score.'/10</span>'
                    : '-'
                )

                ->editColumn('created_at', function ($row) {
                    return $row->created_at->format('M d, Y');
                })

                ->editColumn('status', function ($row) {

                    $class = match($row->status) {
                        'new' => 'bg-info',
                        'reviewing' => 'bg-warning',
                        'shortlisted' => 'bg-primary',
                        'hired' => 'bg-success',
                        'rejected' => 'bg-danger',
                        default => 'bg-secondary'
                    };

                    return '<span class="badge '.$class.'">'.ucfirst($row->status).'</span>';
                })

                ->addColumn('action', function ($row) {
                    return '<a href="'.route('careers.applications.show',$row).'" class="btn btn-sm btn-info">View</a>';
                })

                ->rawColumns(['status','score','action'])
                ->make(true);
        }

        // Job titles for filter dropdown
        $jobTitles = Application::select('job_title')
            ->groupBy('job_title')
            ->pluck('job_title');

        return view('careers::applications.index', compact('jobTitles'));
    }

    /**
     * Display the specified application.
     */
    public function show(Application $application)
    {
        $application->load(['company', 'notes']);
        return view('careers::applications.show', compact('application'));
    }

    /**
     * Update the status and score of an application.
     */
    public function update(Request $request, Application $application)
    {
        $request->validate([
            'status' => 'required|string',
            'score' => 'nullable|integer|min:1|max:10'
        ]);

        $application->update([
            'status' => $request->status,
            'score' => $request->score
        ]);

        return response()->json([
            'message' => 'Application evaluation updated successfully.'
        ]);
    }

    /**
     * Remove the specified application from storage.
     */
    public function destroy(Application $application)
    {
        // delete resume if exists
        if ($application->resume_file) {

            $path = storage_path('app/resumes/' . $application->resume_file);

            if (file_exists($path)) {
                unlink($path);
            }
        }

        $application->delete();

        return response()->json([
            'message' => 'Application deleted successfully.'
        ]);
    }


    public function export(Request $request)
    {
        return Excel::download(
            new ApplicationsExport($request),
            'job_applications.xlsx'
        );
    }
}
