<?php

namespace App\Controllers;

use App\Models\OrganizationModel;

class Dashboard extends BaseController
{
    public function index()
    {
        if ($redirect = $this->requireOrganizationContext()) {
            return $redirect;
        }

        $organizations = new OrganizationModel();
        $db = db_connect();
        $organizationId = $this->currentOrganizationId();

        $siteBuilder = $db->table('sites');
        $turbineBuilder = $db->table('turbines')->join('sites', 'sites.id = turbines.site_id');
        $interventionBuilder = $db->table('maintenance_interventions');
        $taskBuilder = $db->table('maintenance_tasks');

        if (! $this->isPlatformAdmin() && $organizationId !== null) {
            $siteBuilder->where('organization_id', $organizationId);
            $turbineBuilder->where('sites.organization_id', $organizationId);
            $interventionBuilder->where('organization_id', $organizationId);
            $taskBuilder->where('organization_id', $organizationId);
        }

        $latestInterventionsBuilder = $db->table('maintenance_interventions')
            ->select(
                'maintenance_interventions.intervention_code, maintenance_interventions.title, maintenance_interventions.status,' .
                ' maintenance_interventions.completed_at, maintenance_interventions.created_at,' .
                ' organizations.name AS organization_name, sites.name AS site_name, turbines.turbine_code'
            )
            ->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');

        if (! $this->isPlatformAdmin() && $organizationId !== null) {
            $latestInterventionsBuilder->where('maintenance_interventions.organization_id', $organizationId);
        }

        return view('dashboard/index', [
            'title' => 'Dashboard',
            'active' => 'dashboard',
            'stats' => [
                'organizations' => $this->isPlatformAdmin()
                    ? $organizations->countAllResults()
                    : count($organizations->forUser((int) $this->authUser()['id'])),
                'sites' => $siteBuilder->countAllResults(),
                'turbines' => $turbineBuilder->countAllResults(),
                'tasks' => $taskBuilder->countAllResults(),
                'interventions' => $interventionBuilder->countAllResults(),
            ],
            'latestInterventions' => $latestInterventionsBuilder
                ->orderBy('maintenance_interventions.created_at', 'DESC')
                ->get(6)
                ->getResultArray(),
        ]);
    }
}
