<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Employee;
use App\Models\Training;
use Illuminate\Support\Facades\DB;

class TrainingController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index(Request $request)
    {
        $user  = auth()->user();
        $query = Training::withCount('participants')->with('creator');

        if ($request->status) $query->where('status', $request->status);
        if ($request->type)   $query->where('type',   $request->type);
        if ($request->search) {
            $s = $request->search;
            $query->where(fn($q) =>
                $q->where('title', 'like', "%$s%")
                  ->orWhere('description', 'like', "%$s%")
            );
        }

        if ($user->isEmployee() && $request->enrolled_only && $user->employee) {
            $query->whereHas('participants', fn($q) =>
                $q->where('employee_id', $user->employee->id)
            );
        }

        $trainings = $query->latest()->paginate(12)->withQueryString();

        $totals = [
            'total'     => Training::count(),
            'ongoing'   => Training::where('status', 'ongoing')->count(),
            'scheduled' => Training::where('status', 'scheduled')->count(),
            'enrolled'  => $user->isEmployee() && $user->employee
                ? Training::whereHas('participants', fn($q) =>
                    $q->where('employee_id', $user->employee->id)
                  )->count()
                : DB::table('training_participants')->count(),
        ];

        return view('training.index', compact('trainings', 'totals'));
    }

    public function create()
    {
        abort_if(! auth()->user()->isHrOrAdmin(), 403);
        return view('training.create');
    }

    public function store(Request $request)
    {
        abort_if(! auth()->user()->isHrOrAdmin(), 403);

        $request->validate([
            'title'      => 'required|string|max:200',
            'type'       => 'required|string',
            'start_date' => 'required|date',
            'end_date'   => 'required|date|after_or_equal:start_date',
        ]);

        $training = Training::create(
            $request->except(['_token']) + ['created_by' => auth()->id()]
        );

        return redirect()->route('training.show', $training)
                         ->with('success', 'Training program created.');
    }

    public function show(Training $training)
    {
        $training->load(['participants.user', 'creator']);
        $enrolled  = $training->participants->pluck('id');
        $available = Employee::where('status', 'active')
                             ->with('user')
                             ->whereNotIn('id', $enrolled)
                             ->get();

        return view('training.show', compact('training', 'available'));
    }

    public function enroll(Request $request, Training $training)
    {
        abort_if(! auth()->user()->isHrOrAdmin(), 403);

        $request->validate([
            'employee_ids'   => 'required|array',
            'employee_ids.*' => 'exists:employees,id',
        ]);

        foreach ($request->employee_ids as $id) {
            $training->participants()->syncWithoutDetaching([
                $id => ['status' => 'enrolled'],
            ]);
        }

        return back()->with('success', count($request->employee_ids) . ' employee(s) enrolled.');
    }

    public function selfEnroll(Training $training)
    {
        $employee = auth()->user()->employee;
        if (! $employee) return back()->with('error', 'Employee profile not found.');

        $training->participants()->syncWithoutDetaching([
            $employee->id => ['status' => 'enrolled'],
        ]);

        return back()->with('success', 'You have enrolled in ' . $training->title . '.');
    }

    public function complete(Request $request, Training $training, Employee $employee)
    {
        abort_if(! auth()->user()->isHrOrAdmin(), 403);

        $training->participants()->updateExistingPivot($employee->id, [
            'status'             => 'completed',
            'score'              => $request->score,
            'certificate_issued' => $request->boolean('certificate_issued'),
            'certificate_date'   => today(),
        ]);

        return back()->with('success', 'Training completion recorded.');
    }
}
