<?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;
use App\Modules\HR\Models\HrWorkSchedule;

class WorkScheduleController extends Controller
{
    public function index(Request $request): Response
    {
        $db = App::getInstance()->db();
        $schedules = $db->select(
            "SELECT ws.*,
                    (SELECT COUNT(*) FROM hr_employee_schedules es WHERE es.schedule_id = ws.id AND es.is_active = 1) as employee_count
             FROM hr_work_schedules ws
             WHERE ws.is_archived = 0
             ORDER BY ws.name_ar ASC"
        );

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

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

    public function store(Request $request): Response
    {
        $data = $this->extractData($request);
        $errors = $this->validateInput($data);

        if (!empty($errors)) {
            return $this->flashErrorsAndRedirect($errors, $request, '/hr/schedules/create');
        }

        HrWorkSchedule::create($data);

        return $this->redirect('/hr/schedules')->withSuccess('تم إنشاء جدول العمل بنجاح');
    }

    public function edit(Request $request, string $id): Response
    {
        $schedule = HrWorkSchedule::find((int) $id);
        if (!$schedule) {
            return $this->redirect('/hr/schedules')->withError('جدول العمل غير موجود');
        }

        return $this->view('HR.Views.schedules.form', [
            'schedule' => $schedule,
        ]);
    }

    public function update(Request $request, string $id): Response
    {
        $schedule = HrWorkSchedule::find((int) $id);
        if (!$schedule) {
            return $this->redirect('/hr/schedules')->withError('جدول العمل غير موجود');
        }

        $data = $this->extractData($request);
        $errors = $this->validateInput($data);

        if (!empty($errors)) {
            return $this->flashErrorsAndRedirect($errors, $request, '/hr/schedules/' . $id . '/edit');
        }

        $schedule->update($data);

        return $this->redirect('/hr/schedules')->withSuccess('تم تحديث جدول العمل بنجاح');
    }

    private function extractData(Request $request): array
    {
        // Build days_config JSON from form inputs
        $daysOfWeek = ['saturday', 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday'];
        $daysConfig = [];

        foreach ($daysOfWeek as $day) {
            $isWorking = (int) ($request->post('day_' . $day . '_working', 0));
            $daysConfig[$day] = [
                'is_working' => (bool) $isWorking,
                'start_time' => $isWorking ? trim((string) $request->post('day_' . $day . '_start', '09:00')) : null,
                'end_time'   => $isWorking ? trim((string) $request->post('day_' . $day . '_end', '17:00')) : null,
            ];
        }

        return [
            'name_ar'               => trim((string) $request->post('name_ar', '')),
            'name_en'               => trim((string) $request->post('name_en', '')) ?: null,
            'code'                  => strtoupper(trim((string) $request->post('code', ''))),
            'schedule_type'         => trim((string) $request->post('schedule_type', 'fixed')),
            'working_days_per_week' => (int) $request->post('working_days_per_week', 6),
            'hours_per_day'         => trim((string) $request->post('hours_per_day', '8.00')),
            'hours_per_week'        => trim((string) $request->post('hours_per_week', '48.00')),
            'ramadan_hours_per_day' => trim((string) $request->post('ramadan_hours_per_day', '')) ?: null,
            'is_night_shift'        => (int) ($request->post('is_night_shift', 0)),
            'days_config_json'      => json_encode($daysConfig, JSON_UNESCAPED_UNICODE),
            'is_active'             => (int) ($request->post('is_active', 1)),
        ];
    }

    private function validateInput(array $data): array
    {
        $errors = [];
        if ($data['name_ar'] === '' || mb_strlen($data['name_ar']) < 2) {
            $errors[] = 'اسم جدول العمل بالعربي مطلوب';
        }
        if ($data['code'] === '') {
            $errors[] = 'كود جدول العمل مطلوب';
        }
        if ((int) $data['working_days_per_week'] < 1 || (int) $data['working_days_per_week'] > 7) {
            $errors[] = 'عدد أيام العمل يجب أن يكون بين 1 و 7';
        }
        if (bccomp($data['hours_per_day'], '0', 2) <= 0 || bccomp($data['hours_per_day'], '12', 2) > 0) {
            $errors[] = 'ساعات العمل اليومية يجب أن تكون بين 0 و 12';
        }
        return $errors;
    }

    private function flashErrorsAndRedirect(array $errors, Request $request, string $url): Response
    {
        $session = App::getInstance()->session();
        $session->flash('_alerts', array_map(fn($e) => ['type' => 'error', 'message' => $e], $errors));
        $session->flash('_old_input', $request->all());
        return $this->redirect($url);
    }
}
