<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Department;
use App\Models\Designation;
use App\Models\Promotion;
use App\Models\User;
use Illuminate\Http\Request;

class PromotionController extends Controller
{
    public function index()
    {
        $promotions = Promotion::with(['user', 'fromDesignation', 'toDesignation', 'fromDepartment', 'toDepartment'])
            ->orderByDesc('promotion_date')->paginate(15);
        return view('hr.promotions', compact('promotions'));
    }

    public function create()
    {
        $users = User::forActiveDirectory();
        if (auth()->user()->company_id) {
            $users->where('company_id', auth()->user()->company_id);
        }
        $users = $users->orderBy('name')->get();
        $departments = Department::orderBy('name')->get();
        $designations = Designation::orderBy('name')->get();
        return view('hr.promotions-create', compact('users', 'departments', 'designations'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'user_id' => 'required|exists:users,id',
            'from_designation_id' => 'nullable|exists:designations,id',
            'to_designation_id' => 'nullable|exists:designations,id',
            'from_department_id' => 'nullable|exists:departments,id',
            'to_department_id' => 'nullable|exists:departments,id',
            'promotion_date' => 'required|date',
            'notes' => 'nullable|string|max:1000',
        ]);
        $validated['company_id'] = auth()->user()->company_id;
        Promotion::create($validated);
        return redirect()->route('promotions.index')->with('success', 'Promotion recorded successfully.');
    }
}
