<?php

namespace App\Controllers;

use Config\App;

class Audit extends BaseController
{
    public function index()
    {
        $session = session();
        $config = config(App::class);
        $locale = $session->get('locale');

        if (! in_array($locale, $config->supportedLocales, true)) {
            $locale = $config->defaultLocale;
            $session->set('locale', $locale);
        }

        service('request')->setLocale($locale);

        $query = trim((string) $this->request->getGet('q'));
        $result = null;

        if ($query !== '') {
            $builder = db_connect()->table('maintenance_interventions')
                ->select(
                    'maintenance_interventions.*, organizations.name AS organization_name,' .
                    ' sites.name AS site_name, 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');

            $result = $builder->get()->getRowArray();
        }

        return view('audit/index', [
            'query' => $query,
            'result' => $result,
            'currentLocale' => $locale,
            'supportedLocales' => $config->supportedLocales,
        ]);
    }
}
