<?php

namespace Modules\Scheduling\Controllers;

use App\Controllers\BaseController;
use App\Models\AttendanceShiftModel;
use App\Models\EmployeeShiftAssignmentModel;
use Modules\Scheduling\Services\SchedulingService;

class ShiftPlanningController extends BaseController
{
    protected SchedulingService $service;
    protected AttendanceShiftModel $shifts;
    protected EmployeeShiftAssignmentModel $assignments;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->service     = new SchedulingService();
        $this->shifts      = new AttendanceShiftModel();
        $this->assignments = new EmployeeShiftAssignmentModel();
    }

    public function index()
    {
        $employeeId = (int) ($this->request->getGet('employee_id') ?: 0);
        $shiftId    = (int) ($this->request->getGet('shift_id') ?: 0);

        $builder = $this->assignments
            ->select('employee_shift_assignments.*, e.full_name, e.employee_number, s.name as shift_name, s.code as shift_code, s.start_time, s.end_time')
            ->join('employees e', 'e.id = employee_shift_assignments.employee_id')
            ->join('attendance_shifts s', 's.id = employee_shift_assignments.shift_id')
            ->where('e.deleted_at', null);

        if ($employeeId > 0) {
            $builder->where('employee_shift_assignments.employee_id', $employeeId);
        }
        if ($shiftId > 0) {
            $builder->where('employee_shift_assignments.shift_id', $shiftId);
        }

        $rows = $builder->orderBy('employee_shift_assignments.effective_from', 'DESC')->findAll();

        return view('Modules\Scheduling\Views\shifts\index', array_merge($this->baseViewData(), [
            'title'       => 'Shift Planning',
            'assignments' => $rows,
            'employees'   => $this->service->activeEmployees(),
            'shifts'      => $this->shifts->where('status', 'active')->orderBy('name', 'ASC')->findAll(),
            'filters'     => [
                'employee_id' => $employeeId,
                'shift_id'    => $shiftId,
            ],
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'employee_id'    => 'required|is_natural_no_zero',
            'shift_id'       => 'required|is_natural_no_zero',
            'effective_from' => 'required|valid_date',
            'effective_to'   => 'permit_empty|valid_date',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->assignShift(
            $this->request->getPost(),
            (int) $this->session->get('user_id')
        );

        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/scheduling/shifts')->with('success', 'Shift plan created for employee.');
    }

    public function remove(int $id)
    {
        $result = $this->service->removeShiftAssignment($id);
        if (! $result['success']) {
            return redirect()->to('/scheduling/shifts')->with('error', $result['errors']['id'] ?? 'Could not remove.');
        }

        return redirect()->to('/scheduling/shifts')->with('success', 'Shift plan removed.');
    }
}
