<?php

namespace Modules\Patient\Repositories;

use Modules\Patient\DTO\PatientSettingFilter;
use Modules\Patient\Models\ZakatFund;

class ZakatFundRepository
{
    public function all(PatientSettingFilter $filter, array $columns = ['*'])
    {
        return ZakatFund::query()
            ->select($columns)
            ->search($filter->search)
            ->where('status', '=', $filter->status)
            ->where('is_synced', '=', $filter->is_synced)
            ->orderBy('priority', 'asc')
            ->paginate($filter->perPage ?? 15);
    }

    public function find($id)
    {
        return ZakatFund::findOrFail($id);
    }

    public function syncFromErp(array $data)
    {
        ZakatFund::updateOrCreate(
            ['code' => $data['code']],
            [
                'name'     => $data['name'],
                'status'   => $data['status'],
                'priority' => $data['priority'],
                'amount'   => $data['amount'],
            ]
        );
    }

    public function create(array $data)
    {
        return ZakatFund::create([
            'name'       => $data['name'],
            'code'       => $data['code'] ?? null,
            'priority'   => $data['priority'] ?? null,
            'amount'     => $data['amount'] ?? null,
            'status'     => $data['status'],
        ]);
    }

    public function update(ZakatFund $zakatFund, array $data)
    {
        $zakatFund->update([
            'name'       => $data['name'],
            'code'       => $data['code'],
            'amount'     => $data['amount'],
            'status'     => $data['status'],
        ]);

        return $zakatFund;
    }

    public function updateStatus(ZakatFund $zakatFund, array $status)
    {
        $zakatFund->update([
            'status' => $status['status'],
        ]);

        return $zakatFund;
    }

    public function updatePriority(int $id, int $priority): void
    {
        ZakatFund::query()
            ->where('id', $id)
            ->update([
                'priority' => $priority,
            ]);
    }
}
