<?php
declare(strict_types=1);

namespace App\Modules\HR\Models;

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

class HrPayrollPeriod extends Model
{
    protected static string $table = 'hr_payroll_periods';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;
    protected static bool $autoTrackAuthor = true;

    protected static array $fillable = [
        'period_code', 'year', 'month', 'start_date', 'end_date',
        'status', 'total_gross', 'total_deductions', 'total_net',
        'employee_count', 'calculated_at', 'calculated_by',
        'approved_at', 'approved_by', 'paid_at', 'paid_by',
        'closed_at', 'closed_by', 'notes',
    ];

    public static function getStatuses(): array
    {
        return [
            'open'       => 'مفتوح',
            'processing' => 'قيد المعالجة',
            'calculated' => 'تم الحساب',
            'approved'   => 'معتمد',
            'paid'       => 'تم الصرف',
            'closed'     => 'مغلق',
        ];
    }

    public static function getCurrent(): ?array
    {
        $db = App::getInstance()->db();
        return $db->selectOne(
            "SELECT * FROM hr_payroll_periods WHERE status IN ('open','processing','calculated') ORDER BY year DESC, month DESC LIMIT 1"
        );
    }

    public static function getByYearMonth(int $year, int $month): ?array
    {
        $db = App::getInstance()->db();
        return $db->selectOne(
            "SELECT * FROM hr_payroll_periods WHERE year = ? AND month = ?",
            [$year, $month]
        );
    }

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

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

        $countRow = $db->selectOne("SELECT COUNT(*) as cnt FROM hr_payroll_periods WHERE {$where}", $params);
        $total = (int) ($countRow['cnt'] ?? 0);
        $offset = ($page - 1) * $perPage;

        $rows = $db->select(
            "SELECT * FROM hr_payroll_periods WHERE {$where} ORDER BY year DESC, month DESC LIMIT {$perPage} OFFSET {$offset}",
            $params
        );

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