<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Http\Requests\Hr\AssignShiftRequest;
use App\Http\Requests\Hr\StoreShiftRequest;
use App\Models\AuditLog;
use App\Models\Branch;
use App\Models\Department;
use App\Models\Employee;
use App\Models\Shift;
use App\Models\ShiftAssignment;
use Illuminate\Http\Request;

class ShiftController extends Controller
{
    public function index(Request $request)
    {
        $tenantId = $request->user()->tenant_id;
        $shifts = Shift::with(['branch', 'department', 'assignments.employee', 'assignments.department', 'assignments.branch'])->orderBy('name')->paginate(15);
        $employees = Employee::where('status', 'active')->orderBy('full_name')->get(['id', 'full_name', 'employee_code']);
        $branches = Branch::where('tenant_id', $tenantId)->orderBy('name')->get();
        $departments = Department::where('tenant_id', $tenantId)->orderBy('name')->get();

        return view('tenant.hr.shifts.index', compact('shifts', 'employees', 'branches', 'departments'));
    }

    public function store(StoreShiftRequest $request)
    {
        $data = $request->validated();
        $data['tenant_id'] = $request->user()->tenant_id;
        $data['is_active'] = $request->boolean('is_active', true);
        $data['applicable_days'] = $data['applicable_days'] ?? ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
        $shift = Shift::create($data);
        AuditLog::record('shifts', 'shift.created', $shift, null, $shift->toArray(), $request->user());

        return back()->with('status', 'Shift created successfully.');
    }

    public function update(StoreShiftRequest $request, int $id)
    {
        $shift = Shift::findOrFail($id);
        $before = $shift->toArray();
        $data = $request->validated();
        $data['is_active'] = $request->boolean('is_active');
        $shift->update($data);
        AuditLog::record('shifts', 'shift.updated', $shift, $before, $shift->fresh()->toArray(), $request->user());

        return back()->with('status', 'Shift updated.');
    }

    public function assign(AssignShiftRequest $request, int $id)
    {
        $shift = Shift::findOrFail($id);
        $data = $request->validated();
        $assignment = ShiftAssignment::create($data + ['tenant_id' => $request->user()->tenant_id, 'shift_id' => $shift->id, 'assigned_by' => $request->user()->id]);
        AuditLog::record('shifts', 'shift.assigned', $assignment, null, $assignment->toArray(), $request->user());

        return back()->with('status', 'Shift assignment saved with effective-date history.');
    }
}
