<?php

namespace App\Controllers\Api;

use App\Models\BlockchainTransactionModel;

class Blockchain extends BaseApiController
{
    public function index()
    {
        if ($response = $this->requireAnyApiScope(['blockchain:read', 'maintenance:read', 'certificates:read'])) {
            return $response;
        }

        $builder = (new BlockchainTransactionModel())
            ->withIntervention()
            ->join('sites', 'sites.id = maintenance_interventions.site_id')
            ->where('maintenance_interventions.organization_id', $this->apiOrganizationId());

        $status = trim((string) $this->request->getGet('status'));
        if ($status !== '') {
            $builder->where('blockchain_transactions.status', $status);
        }

        $code = trim((string) $this->request->getGet('intervention_code'));
        if ($code !== '') {
            $builder->where('maintenance_interventions.intervention_code', $code);
        }

        return $this->respondOk(
            $builder->orderBy('blockchain_transactions.created_at', 'DESC')->findAll(100)
        );
    }
}
