<?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\Services\OvertimeService;

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

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

        if ($status) {
            $where .= ' AND r.status = ?';
            $params[] = $status;
        }

        $requests = $db->select(
            "SELECT r.*, e.full_name_ar as employee_name, t.name_ar as type_name, t.rate_multiplier,
                    ap.full_name_ar as approved_by_name
             FROM hr_overtime_requests r
             JOIN employees e ON e.id = r.employee_id
             JOIN hr_overtime_types t ON t.id = r.overtime_type_id
             LEFT JOIN employees ap ON ap.id = r.approved_by
             WHERE {$where}
             ORDER BY r.request_date DESC, r.created_at DESC",
            $params
        );

        $types = $db->select("SELECT * FROM hr_overtime_types WHERE is_active = 1");

        return $this->view('HR.Views.overtime.index', [
            'requests' => $requests,
            'types' => $types,
            'status' => $status,
            'month' => $month,
        ]);
    }

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

        $employees = $db->select("SELECT id, full_name_ar, employee_number FROM employees WHERE is_archived = 0 AND employment_status = 'active' ORDER BY full_name_ar");
        $types = $db->select("SELECT * FROM hr_overtime_types WHERE is_active = 1");

        return $this->view('HR.Views.overtime.form', [
            'employees' => $employees,
            'types' => $types,
        ]);
    }

    public function store(Request $request): Response
    {
        $this->authorize('hr.overtime.create');

        $data = [
            'employee_id' => (int) $request->post('employee_id'),
            'overtime_type_id' => (int) $request->post('overtime_type_id'),
            'request_date' => $request->post('request_date'),
            'start_time' => $request->post('start_time'),
            'end_time' => $request->post('end_time'),
            'reason' => $request->post('reason'),
        ];

        $result = OvertimeService::submitRequest($data);

        if (!$result['success']) {
            return $this->redirect('/hr/overtime/create')->withError($result['error']);
        }

        return $this->redirect('/hr/overtime')->withSuccess('تم تقديم طلب العمل الإضافي — ' . $result['hours'] . ' ساعة');
    }

    public function approve(Request $request, string $id): Response
    {
        $this->authorize('hr.overtime.approve');

        $result = OvertimeService::approve((int) $id);

        if (!$result['success']) {
            return $this->redirect('/hr/overtime')->withError($result['error']);
        }

        return $this->redirect('/hr/overtime')->withSuccess('تم اعتماد طلب العمل الإضافي');
    }

    public function reject(Request $request, string $id): Response
    {
        $this->authorize('hr.overtime.approve');

        $reason = (string) $request->post('rejection_reason', '');
        OvertimeService::reject((int) $id, $reason);

        return $this->redirect('/hr/overtime')->withSuccess('تم رفض طلب العمل الإضافي');
    }

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

        $types = $db->select("SELECT * FROM hr_overtime_types ORDER BY created_at DESC");

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

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

        $db->insert('hr_overtime_types', [
            'name_ar' => $request->post('name_ar'),
            'name_en' => $request->post('name_en'),
            'rate_multiplier' => $request->post('rate_multiplier', '1.50'),
            'max_hours_per_day' => $request->post('max_hours_per_day') ?: null,
            'max_hours_per_month' => $request->post('max_hours_per_month') ?: null,
            'requires_approval' => (int) $request->post('requires_approval', 1),
        ]);

        return $this->redirect('/hr/overtime/types')->withSuccess('تم إضافة نوع العمل الإضافي');
    }
}
