<?php

namespace App\Services;

use App\Models\Equipment\Equipment;
use App\Models\Equipment\EquipmentInspection;
use App\Models\Equipment\EquipmentInspectionDetail;
use App\Models\Equipment\EquipmentInspectionTemplate;
use Carbon\Carbon;

class EquipmentInspectionService
{
    public function getMonthlyInspections(string $yearMonth, ?string $productionLine = null, ?int $equipmentId = null): array
    {
        $tenantId = session('selected_tenant_id', 1);

        $equipmentQuery = Equipment::where('is_active', true)->where('status', '!=', 'disposed');

        if ($productionLine) {
            $equipmentQuery->where('production_line', $productionLine);
        }

        if ($equipmentId) {
            $equipmentQuery->where('id', $equipmentId);
        }

        $equipments = $equipmentQuery->orderBy('sort_order')->orderBy('name')->get();

        $date = Carbon::createFromFormat('Y-m', $yearMonth);
        $daysInMonth = $date->daysInMonth;

        $result = [];

        foreach ($equipments as $equipment) {
            $templates = EquipmentInspectionTemplate::where('equipment_id', $equipment->id)
                ->where('is_active', true)
                ->orderBy('sort_order')
                ->get();

            if ($templates->isEmpty()) {
                continue;
            }

            $inspection = EquipmentInspection::where('equipment_id', $equipment->id)
                ->where('year_month', $yearMonth)
                ->first();

            $details = [];
            if ($inspection) {
                $details = EquipmentInspectionDetail::where('inspection_id', $inspection->id)
                    ->get()
                    ->groupBy(function ($d) {
                        return $d->template_item_id.'_'.$d->check_date->format('Y-m-d');
                    });
            }

            $result[] = [
                'equipment' => $equipment,
                'templates' => $templates,
                'inspection' => $inspection,
                'details' => $details,
                'days_in_month' => $daysInMonth,
            ];
        }

        return $result;
    }

    public function toggleDetail(int $equipmentId, int $templateItemId, string $checkDate): array
    {
        $tenantId = session('selected_tenant_id', 1);
        $yearMonth = Carbon::parse($checkDate)->format('Y-m');

        $inspection = EquipmentInspection::firstOrCreate(
            [
                'tenant_id' => $tenantId,
                'equipment_id' => $equipmentId,
                'year_month' => $yearMonth,
            ],
            [
                'created_by' => auth()->id(),
            ]
        );

        $detail = EquipmentInspectionDetail::where('inspection_id', $inspection->id)
            ->where('template_item_id', $templateItemId)
            ->where('check_date', $checkDate)
            ->first();

        if ($detail) {
            $nextResult = EquipmentInspectionDetail::getNextResult($detail->result);
            if ($nextResult === null) {
                $detail->delete();

                return ['result' => null, 'symbol' => '', 'color' => 'text-gray-400'];
            }
            $detail->update(['result' => $nextResult]);
        } else {
            $detail = EquipmentInspectionDetail::create([
                'inspection_id' => $inspection->id,
                'template_item_id' => $templateItemId,
                'check_date' => $checkDate,
                'result' => 'good',
            ]);
            $nextResult = 'good';
        }

        return [
            'result' => $nextResult,
            'symbol' => $detail->fresh()->result_symbol,
            'color' => $detail->fresh()->result_color,
        ];
    }

    public function updateInspectionNotes(int $equipmentId, string $yearMonth, array $data): EquipmentInspection
    {
        $tenantId = session('selected_tenant_id', 1);

        $inspection = EquipmentInspection::firstOrCreate(
            [
                'tenant_id' => $tenantId,
                'equipment_id' => $equipmentId,
                'year_month' => $yearMonth,
            ],
            [
                'created_by' => auth()->id(),
            ]
        );

        $inspection->update(array_merge($data, ['updated_by' => auth()->id()]));

        return $inspection->fresh();
    }

    public function getMonthlyStats(string $yearMonth): array
    {
        $tenantId = session('selected_tenant_id', 1);

        $totalEquipments = Equipment::where('is_active', true)
            ->where('status', '!=', 'disposed')
            ->count();

        $inspected = EquipmentInspection::where('year_month', $yearMonth)->count();

        $issueCount = EquipmentInspectionDetail::whereHas('inspection', function ($q) use ($yearMonth) {
            $q->where('year_month', $yearMonth);
        })->where('result', 'bad')->count();

        return [
            'total' => $totalEquipments,
            'inspected' => $inspected,
            'issue_count' => $issueCount,
        ];
    }

    public function saveTemplate(int $equipmentId, array $data): EquipmentInspectionTemplate
    {
        $tenantId = session('selected_tenant_id', 1);

        return EquipmentInspectionTemplate::create(array_merge($data, [
            'tenant_id' => $tenantId,
            'equipment_id' => $equipmentId,
        ]));
    }

    public function updateTemplate(int $id, array $data): EquipmentInspectionTemplate
    {
        $template = EquipmentInspectionTemplate::findOrFail($id);
        $template->update($data);

        return $template->fresh();
    }

    public function deleteTemplate(int $id): bool
    {
        return EquipmentInspectionTemplate::findOrFail($id)->delete();
    }
}
