<?php

namespace Modules\Attendance\Controllers;

use App\Controllers\BaseController;
use App\Models\AttendanceShiftModel;
use App\Models\EmployeeModel;
use App\Models\EmployeeShiftAssignmentModel;
use Modules\Attendance\Services\AttendanceShiftService;
use Modules\Attendance\Services\ShiftAssignmentService;

class AttendanceShiftController extends BaseController
{
    protected AttendanceShiftModel $shifts;
    protected EmployeeModel $employees;
    protected EmployeeShiftAssignmentModel $assignments;
    protected AttendanceShiftService $service;
    protected ShiftAssignmentService $assignmentService;

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

    public function index()
    {
        $search = trim((string) $this->request->getGet('q'));
        $status = $this->request->getGet('status') ?: null;

        $shifts = $this->shifts
            ->scopeForList($search ?: null, $status)
            ->orderBy('name', 'ASC')
            ->findAll();

        return view('Modules\Attendance\Views\shifts\index', array_merge($this->baseViewData(), [
            'title'   => 'Attendance Shifts',
            'shifts'  => $shifts,
            'filters' => compact('search', 'status'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Attendance\Views\shifts\create', array_merge($this->baseViewData(), [
            'title' => 'Add Shift',
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'name'       => 'required|min_length[2]|max_length[100]',
            'code'       => 'required|max_length[10]',
            'start_time' => 'required',
            'end_time'   => 'required',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->create($this->request->getPost(), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/attendance/shifts')->with('success', 'Shift created.');
    }

    public function editForm(int $id)
    {
        $shift = $this->shifts->find($id);
        if (! $shift) {
            return redirect()->to('/attendance/shifts')->with('error', 'Shift not found.');
        }

        return view('Modules\Attendance\Views\shifts\edit', array_merge($this->baseViewData(), [
            'title' => 'Edit Shift',
            'shift' => $shift,
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'name'       => 'required|min_length[2]|max_length[100]',
            'code'       => 'required|max_length[10]',
            'start_time' => 'required',
            'end_time'   => 'required',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->update($id, $this->request->getPost(), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/attendance/shifts')->with('success', 'Shift updated.');
    }

    public function activate(int $id)
    {
        $this->service->activate($id, (int) $this->session->get('user_id'));

        return redirect()->back()->with('success', 'Shift activated.');
    }

    public function deactivate(int $id)
    {
        $this->service->deactivate($id, (int) $this->session->get('user_id'));

        return redirect()->back()->with('success', 'Shift deactivated.');
    }

    public function destroy(int $id)
    {
        $result = $this->service->delete($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->to('/attendance/shifts')->with('error', $result['error']);
        }

        return redirect()->to('/attendance/shifts')->with('success', 'Shift deleted.');
    }

    public function assignments()
    {
        $employeeId = $this->request->getGet('employee_id') ? (int) $this->request->getGet('employee_id') : null;

        $builder = $this->assignments
            ->select('employee_shift_assignments.*, e.full_name, e.employee_number, s.name as shift_name, s.code as shift_code')
            ->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) {
            $builder->where('employee_shift_assignments.employee_id', $employeeId);
        }

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

        return view('Modules\Attendance\Views\shifts\assignments', array_merge($this->baseViewData(), [
            'title'       => 'Shift Assignments',
            'assignments' => $assignments,
            'employees'   => $this->employees->scopeForList(null, 'active')->orderBy('full_name', 'ASC')->findAll(),
            'shifts'      => $this->shifts->getActive(),
            'employeeId'  => $employeeId,
        ]));
    }

    public function assignStore()
    {
        if (! $this->validate([
            'employee_id'    => 'required|integer',
            'shift_id'       => 'required|integer',
            'effective_from' => 'required|valid_date[Y-m-d]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->assignmentService->assign($this->request->getPost(), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/attendance/shifts/assignments')->with('success', 'Shift assigned to employee.');
    }
}
