<?php
declare(strict_types=1);

namespace App\Modules\Death\Models;

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

class DeathCase extends Model
{
    protected static string $table = 'death_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', 'deceased_type', 'death_date',
        'death_certificate_number', 'death_certificate_path',
        'spouse_id', 'primary_spouse_id', 'secondary_spouses_json',
        'primary_spouse_form_filled', 'child_id',
        'children_assignment_json', 'transferred_to_member_id',
        'same_membership_number', 'fee_amount',
        '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 death_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
             FROM death_cases dc JOIN members m ON m.id = dc.member_id
             WHERE {$where} ORDER BY dc.created_at DESC LIMIT {$perPage} OFFSET {$offset}", $params
        );
        return ['data' => $rows, 'pagination' => Pagination::paginate($total, $perPage, $page)];
    }
}