<?php
declare(strict_types=1);

namespace App\Modules\HR\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;

class ShiftController extends Controller
{
    public function index(Request $request): Response
    {
        $this->authorize('hr.shifts.view');
        $db = App::getInstance()->db();

        $shifts = $db->select("SELECT * FROM hr_shifts ORDER BY start_time ASC");

        return $this->view('HR.Views.shifts.index', ['shifts' => $shifts]);
    }

    public function create(Request $request): Response
    {
        $this->authorize('hr.shifts.manage');
        return $this->view('HR.Views.shifts.form', ['shift' => null]);
    }

    public function store(Request $request): Response
    {
        $this->authorize('hr.shifts.manage');
        $db = App::getInstance()->db();

        $startTime = $request->post('start_time');
        $endTime = $request->post('end_time');
        $breakDuration = (int) $request->post('break_duration_minutes', 0);

        $startMin = self::timeToMinutes($startTime);
        $endMin = self::timeToMinutes($endTime);
        if ($endMin <= $startMin) $endMin += 1440;
        $workingHours = ($endMin - $startMin - $breakDuration) / 60;

        $db->insert('hr_shifts', [
            'name_ar' => $request->post('name_ar'),
            'name_en' => $request->post('name_en'),
            'start_time' => $startTime,
            'end_time' => $endTime,
            'break_start' => $request->post('break_start') ?: null,
            'break_end' => $request->post('break_end') ?: null,
            'break_duration_minutes' => $breakDuration,
            'working_hours' => number_format($workingHours, 2),
            'grace_period_minutes' => (int) $request->post('grace_period_minutes', 15),
            'early_leave_threshold_minutes' => (int) $request->post('early_leave_threshold_minutes', 15),
            'is_night_shift' => (int) $request->post('is_night_shift', 0),
        ]);

        return $this->redirect('/hr/shifts')->withSuccess('تم إضافة الوردية بنجاح');
    }

    public function assignments(Request $request): Response
    {
        $this->authorize('hr.shifts.manage');
        $db = App::getInstance()->db();

        $assignments = $db->select(
            "SELECT sa.*, CONCAT(e.first_name_ar, ' ', e.last_name_ar) as employee_name, e.employee_number, s.name_ar as shift_name
             FROM hr_shift_assignments sa
             JOIN hr_employee_profiles e ON e.id = sa.employee_id
             JOIN hr_shifts s ON s.id = sa.shift_id
             WHERE sa.is_active = 1
             ORDER BY e.first_name_ar"
        );

        $employees = $db->select("SELECT id, CONCAT(first_name_ar, ' ', last_name_ar) as full_name_ar, employee_number FROM hr_employee_profiles WHERE is_archived = 0 AND employment_status = 'active' ORDER BY first_name_ar");
        $shifts = $db->select("SELECT id, name_ar FROM hr_shifts WHERE is_active = 1");

        return $this->view('HR.Views.shifts.assignments', [
            'assignments' => $assignments,
            'employees' => $employees,
            'shifts' => $shifts,
        ]);
    }

    public function assignShift(Request $request): Response
    {
        $this->authorize('hr.shifts.manage');
        $db = App::getInstance()->db();

        $employeeId = (int) $request->post('employee_id');
        $shiftId = (int) $request->post('shift_id');

        $db->query(
            "UPDATE hr_shift_assignments SET is_active = 0 WHERE employee_id = ? AND is_active = 1",
            [$employeeId]
        );

        $db->insert('hr_shift_assignments', [
            'employee_id' => $employeeId,
            'shift_id' => $shiftId,
            'start_date' => $request->post('start_date', date('Y-m-d')),
            'end_date' => $request->post('end_date') ?: null,
            'rotation_pattern' => $request->post('rotation_pattern', 'fixed'),
            'is_active' => 1,
        ]);

        return $this->redirect('/hr/shifts/assignments')->withSuccess('تم تعيين الوردية');
    }

    public function violations(Request $request): Response
    {
        $this->authorize('hr.attendance.view');
        $db = App::getInstance()->db();

        $month = $request->get('month', date('Y-m'));
        $type = $request->get('type', '');
        $where = "DATE_FORMAT(v.violation_date, '%Y-%m') = ?";
        $params = [$month];

        if ($type) {
            $where .= ' AND v.violation_type = ?';
            $params[] = $type;
        }

        $violations = $db->select(
            "SELECT v.*, CONCAT(e.first_name_ar, ' ', e.last_name_ar) as employee_name, e.employee_number
             FROM hr_attendance_violations v
             JOIN hr_employee_profiles e ON e.id = v.employee_id
             WHERE {$where}
             ORDER BY v.violation_date DESC, v.created_at DESC",
            $params
        );

        return $this->view('HR.Views.shifts.violations', [
            'violations' => $violations,
            'month' => $month,
            'type' => $type,
        ]);
    }

    private static function timeToMinutes(string $time): int
    {
        $parts = explode(':', $time);
        return ((int) $parts[0]) * 60 + ((int) ($parts[1] ?? 0));
    }
}
