<?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', 'incident_date', 'reported_date', 'incident_description',
        'investigation_notes', 'investigated_by', 'investigation_date',
        'penalty_type', 'penalty_details_json',
        'wage_deduction_days', 'suspension_days',
        'decision_date', 'decided_by', 'decision_notes',
        'appeal_date', 'appeal_reason', 'appeal_decision', 'appeal_decided_by', 'appeal_decision_date',
        'enforcement_date', 'status', 'workflow_instance_id', 'notes',
    ];

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

    public static function getStatuses(): array
    {
        return [
            'reported'            => 'تم الإبلاغ',
            'under_investigation' => 'تحت التحقيق',
            'investigation_done'  => 'انتهى التحقيق',
            'penalty_decided'     => 'تم تحديد العقوبة',
            'enforced'            => 'تم التنفيذ',
            'appealed'            => 'تم التظلم',
            'appeal_reviewed'     => 'تم مراجعة التظلم',
            'upheld'              => 'تم تأييد العقوبة',
            'modified'            => 'تم تعديل العقوبة',
            'overturned'          => 'تم إلغاء العقوبة',
            'dismissed'           => 'تم الحفظ',
            'closed'              => 'مغلق',
        ];
    }

    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(enforcement_date) = ? AND MONTH(enforcement_date) = ?
               AND penalty_type = 'deduction'
               AND status IN ('enforced', 'upheld', 'closed')
               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(enforcement_date) = ? AND MONTH(enforcement_date) = ?
               AND penalty_type = 'suspension'
               AND status IN ('enforced', 'upheld', 'closed')
               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.reported_date DESC
             LIMIT {$perPage} OFFSET {$offset}",
            $params
        );

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