<?php
declare(strict_types=1);

namespace App\Modules\Divorce\Models;

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

class DivorceCase extends Model
{
    protected static string $table = 'divorce_cases';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;
    protected static bool $dispatchEvents = true;

    protected static array $fillable = [
        'member_id', 'spouse_id', 'divorce_date', 'divorce_certificate_path',
        'spouse_qualification_id', 'divorce_case_type',
        'request_date', 'membership_acquisition_date', 'years_of_membership',
        'has_children_on_membership', 'fee_percentage', 'fee_amount',
        'annual_subscription_fee', 'form_fee', 'total_fee',
        'board_decision_number', 'board_decision_date', 'board_notes',
        'spouse_new_member_id', 'spouse_new_membership_number',
        'original_member_id', 'original_membership_number',
        'children_assignment_json', 'archive_snapshot_id',
        'workflow_instance_id', 'status', 'notes',
    ];

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

        if (!empty($filters['status'])) { $where .= ' AND dc.status = ?'; $params[] = $filters['status']; }
        if (!empty($filters['search'])) {
            $where .= ' AND (m.full_name_ar LIKE ? OR m.membership_number LIKE ?)';
            $s = '%' . $filters['search'] . '%'; $params[] = $s; $params[] = $s;
        }

        $countRow = $db->selectOne("SELECT COUNT(*) as cnt FROM divorce_cases dc JOIN members m ON m.id = dc.member_id WHERE {$where}", $params);
        $total = (int) ($countRow['cnt'] ?? 0);
        $offset = ($page - 1) * $perPage;

        $rows = $db->select(
            "SELECT dc.*, m.full_name_ar as member_name, m.membership_number,
                    s.full_name_ar as spouse_name
             FROM divorce_cases dc
             JOIN members m ON m.id = dc.member_id
             JOIN spouses s ON s.id = dc.spouse_id
             WHERE {$where} ORDER BY dc.created_at DESC LIMIT {$perPage} OFFSET {$offset}", $params
        );

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

    public static function getCaseTypeLabel(string $type): string
    {
        return match ($type) {
            'both_working'  => 'كلاهما عامل قبل الزواج',
            'same_form'     => 'قُبلا في استمارة واحدة',
            'joined_after'  => 'الزوج/ة انضم بعد العضوية',
            default         => $type,
        };
    }
}