<?php

namespace App\Controllers\Api;

use App\Controllers\BaseController;

class Audit extends BaseController
{
    public function index()
    {
        $query = trim((string) $this->request->getGet('q'));
        if ($query === '') {
            return $this->response->setStatusCode(422)->setJSON([
                'status' => 'error',
                'message' => 'Query parameter q is required.',
            ]);
        }

        $result = db_connect()->table('maintenance_interventions')
            ->select(
                'maintenance_interventions.*, organizations.name AS organization_name,' .
                ' sites.name AS site_name, sites.site_code, turbines.turbine_code,' .
                ' blockchain_transactions.transaction_hash, blockchain_transactions.network,' .
                ' blockchain_transactions.status AS blockchain_status, blockchain_transactions.anchored_hash'
            )
            ->join('organizations', 'organizations.id = maintenance_interventions.organization_id')
            ->join('sites', 'sites.id = maintenance_interventions.site_id')
            ->join('turbines', 'turbines.id = maintenance_interventions.turbine_id', 'left')
            ->join('blockchain_transactions', 'blockchain_transactions.maintenance_intervention_id = maintenance_interventions.id', 'left')
            ->groupStart()
                ->where('maintenance_interventions.intervention_code', $query)
                ->orWhere('maintenance_interventions.external_reference', $query)
                ->orWhere('blockchain_transactions.transaction_hash', $query)
                ->orWhere('blockchain_transactions.anchored_hash', $query)
            ->groupEnd()
            ->orderBy('maintenance_interventions.created_at', 'DESC')
            ->get()
            ->getRowArray();

        if (! $result) {
            return $this->response->setStatusCode(404)->setJSON([
                'status' => 'error',
                'message' => 'Maintenance intervention not found.',
            ]);
        }

        return $this->response->setJSON([
            'status' => 'ok',
            'data' => $result,
        ]);
    }
}
