<?php
declare(strict_types=1);

namespace App\Modules\HR\Models;

use App\Core\Model;
use App\Core\App;
use App\Core\Pagination;

class HrDisciplinaryAction extends Model
{
    protected static string $table = 'hr_disciplinary_actions';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = true;
    protected static bool $autoTrackAuthor = true;

    protected static array $fillable = [
        'employee_profile_id', 'action_number', 'incident_date', 'incident_description',
        'investigation_notes', 'investigation_by', 'investigation_date',
        'penalty_type', 'penalty_details_json',
        'wage_deduction_days', 'wage_deduction_amount', 'suspension_days',
        'effective_date', 'status',
        'decided_by', 'decided_at',
        'appeal_deadline', 'appeal_text', 'appeal_date',
        'appeal_result', 'appeal_reviewed_by', 'appeal_reviewed_at',
        'workflow_instance_id', 'document_path', 'notes',
    ];

    public static function getPenaltyTypes(): array
    {
        return [
            'warning'            => 'إنذار',
            'wage_deduction'     => 'خصم من الراتب',
            'raise_postponement' => 'تأجيل علاوة',
            'suspension'         => 'إيقاف عن العمل',
            'demotion'           => 'تخفيض الدرجة',
            'termination'        => 'فصل من العمل',
        ];
    }

    public static function getStatuses(): array
    {
        return [
            'investigation'    => 'تحت التحقيق',
            'pending_decision' => 'في انتظار القرار',
            'decided'          => 'تم تحديد العقوبة',
            'appealed'         => 'تم التظلم',
            'appeal_reviewed'  => 'تم مراجعة التظلم',
            'enforced'         => 'تم التنفيذ',
            'cancelled'        => 'ملغى',
        ];
    }

    public static function getMonthlyDeductionDays(int $profileId, int $year, int $month): int
    {
        $db = App::getInstance()->db();
        $row = $db->selectOne(
            "SELECT COALESCE(SUM(wage_deduction_days), 0) as total
             FROM hr_disciplinary_actions
             WHERE employee_profile_id = ?
               AND YEAR(effective_date) = ? AND MONTH(effective_date) = ?
               AND penalty_type = 'wage_deduction'
               AND status IN ('enforced', 'decided')
               AND is_archived = 0",
            [$profileId, $year, $month]
        );
        return (int) ($row['total'] ?? 0);
    }

    public static function getMonthlySuspensionDays(int $profileId, int $year, int $month): int
    {
        $db = App::getInstance()->db();
        $row = $db->selectOne(
            "SELECT COALESCE(SUM(suspension_days), 0) as total
             FROM hr_disciplinary_actions
             WHERE employee_profile_id = ?
               AND YEAR(effective_date) = ? AND MONTH(effective_date) = ?
               AND penalty_type = 'suspension'
               AND status IN ('enforced', 'decided')
               AND is_archived = 0",
            [$profileId, $year, $month]
        );
        return (int) ($row['total'] ?? 0);
    }

    public static function search(array $filters, int $perPage = 25, int $page = 1): array
    {
        $db = App::getInstance()->db();
        $where = 'da.is_archived = 0';
        $params = [];

        if (!empty($filters['employee_profile_id'])) {
            $where .= ' AND da.employee_profile_id = ?';
            $params[] = (int) $filters['employee_profile_id'];
        }
        if (!empty($filters['status'])) {
            $where .= ' AND da.status = ?';
            $params[] = $filters['status'];
        }
        if (!empty($filters['penalty_type'])) {
            $where .= ' AND da.penalty_type = ?';
            $params[] = $filters['penalty_type'];
        }

        $countRow = $db->selectOne(
            "SELECT COUNT(*) as cnt FROM hr_disciplinary_actions da
             JOIN hr_employee_profiles p ON p.id = da.employee_profile_id WHERE {$where}",
            $params
        );
        $total = (int) ($countRow['cnt'] ?? 0);
        $offset = ($page - 1) * $perPage;

        $rows = $db->select(
            "SELECT da.*, CONCAT(p.first_name_ar, ' ', p.last_name_ar) as full_name_ar, p.employee_number
             FROM hr_disciplinary_actions da
             JOIN hr_employee_profiles p ON p.id = da.employee_profile_id
             WHERE {$where}
             ORDER BY da.incident_date DESC
             LIMIT {$perPage} OFFSET {$offset}",
            $params
        );

        return ['data' => $rows, 'pagination' => Pagination::paginate($total, $perPage, $page)];
    }
}
