<?php

namespace App\Http\Controllers;

use App\Models\AnalysisResult;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CompanyController extends Controller
{
    // Tidak pakai __construct middleware — sudah dihandle di web.php route group

    public function index()
    {
        $companies = AnalysisResult::where('user_id', Auth::id())
            ->selectRaw('company_name, business_field,
                MAX(created_at) as last_analysis,
                COUNT(*) as total_analyses,
                AVG(z_score) as avg_zscore,
                MAX(z_score) as max_zscore,
                MIN(z_score) as min_zscore')
            ->groupBy('company_name', 'business_field')
            ->orderByDesc('last_analysis')
            ->get();

        return view('companies.index', compact('companies'));
    }

    public function show($name)
    {
        $name = urldecode($name);

        $analyses = AnalysisResult::where('user_id', Auth::id())
            ->where('company_name', $name)
            ->orderByDesc('created_at')
            ->get();

        if ($analyses->isEmpty()) {
            return redirect()->route('companies.index')
                ->with('error', 'Perusahaan tidak ditemukan.');
        }

        $latest  = $analyses->first();
        $summary = [
            'total'      => $analyses->count(),
            'avg_zscore' => $analyses->avg('z_score'),
            'max_zscore' => $analyses->max('z_score'),
            'min_zscore' => $analyses->min('z_score'),
            'safe'       => $analyses->where('z_category', 'safe')->count(),
            'grey'       => $analyses->where('z_category', 'grey')->count(),
            'distress'   => $analyses->where('z_category', 'distress')->count(),
        ];

        return view('companies.show', compact('analyses', 'latest', 'summary', 'name'));
    }

    public function edit($name)
    {
        $name     = urldecode($name);
        $analyses = AnalysisResult::where('user_id', Auth::id())
            ->where('company_name', $name)
            ->orderByDesc('created_at')
            ->get();

        if ($analyses->isEmpty()) {
            return redirect()->route('companies.index')
                ->with('error', 'Perusahaan tidak ditemukan.');
        }

        return view('companies.edit', compact('analyses', 'name'));
    }

    public function update(Request $request, $name)
    {
        $name    = urldecode($name);
        $newName = $request->validate([
            'company_name' => 'required|string|max:255',
        ])['company_name'];

        AnalysisResult::where('user_id', Auth::id())
            ->where('company_name', $name)
            ->update(['company_name' => $newName]);

        return redirect()->route('companies.show', urlencode($newName))
            ->with('success', 'Nama perusahaan berhasil diperbarui.');
    }

    public function destroy($name)
    {
        $name    = urldecode($name);
        $deleted = AnalysisResult::where('user_id', Auth::id())
            ->where('company_name', $name)
            ->delete();

        return redirect()->route('companies.index')
            ->with($deleted ? 'success' : 'error',
                   $deleted
                       ? "Data perusahaan \"{$name}\" berhasil dihapus."
                       : 'Gagal menghapus data perusahaan.');
    }
}