<?php

namespace App\Http\Controllers;

use App\Models\Production;
use App\Models\ProductionDetail;
use App\Models\Product;
use Illuminate\Http\Request;
use Carbon\Carbon;

class ProductionController extends Controller
{
    public function index(Request $request)
    {
        $startDate = $request->start_date ?? Carbon::now()->subMonths(3)->format('Y-m-d');
        $endDate   = $request->end_date ?? Carbon::now()->format('Y-m-d');

        $productions = Production::whereBetween('production_date', [$startDate, $endDate])
            ->latest()
            ->get();

        $headers = ['Tanggal Produksi', 'Biaya Bahan (Rp)', 'Biaya Operasional (Rp)', 'Catatan', 'Aksi'];

        $rows = $productions->map(function($p) {
            return [
                'cols' => [
                    $p->production_date->format('d F Y'),
                    number_format($p->cost_material, 0, ',', '.'),
                    number_format($p->operational_cost, 0, ',', '.'),
                    $p->notes ?? '-',
                ],
                'actions' => view('components.action-button', [
                    'id' => $p->id,
                    'resource' => 'productions'
                ])->render(),
            ];
        });

        return view('productions.index', compact('headers', 'rows', 'startDate', 'endDate'));
    }

    public function create()
    {
        $products = Product::all();
        return view('productions.create', compact('products'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'production_date' => 'required|date',
            'cost_material' => 'required|numeric|min:0',
            'operational_cost' => 'required|numeric|min:0',
            'notes' => 'nullable|string',
            'products' => 'required|array',
            'products.*.product_id' => 'required|exists:products,id',
            'products.*.quantity' => 'required|integer|min:0',
        ]);

        $production = Production::create([
            'production_date' => $validated['production_date'],
            'cost_material' => $validated['cost_material'],
            'operational_cost' => $validated['operational_cost'],
            'notes' => $validated['notes'] ?? null,
        ]);

        foreach ($validated['products'] as $p) {
            if ($p['quantity'] > 0) {
                ProductionDetail::create([
                    'production_id' => $production->id,
                    'product_id' => $p['product_id'],
                    'quantity' => $p['quantity'],
                ]);
            }
        }

        return redirect()->route('productions.index')->with('success', 'Produksi berhasil disimpan.');
    }

    public function show(Production $production)
    {
        $production->load('details.product');
        return view('productions.show', compact('production'));
    }

    public function edit(Production $production)
    {
        $products = Product::all();
        $production->load('details');

        return view('productions.edit', compact('production', 'products'));
    }

    public function update(Request $request, Production $production)
    {
        $validated = $request->validate([
            'production_date' => 'required|date',
            'cost_material' => 'required|numeric|min:0',
            'operational_cost' => 'required|numeric|min:0',
            'notes' => 'nullable|string',
            'products' => 'required|array',
            'products.*.product_id' => 'required|exists:products,id',
            'products.*.quantity' => 'required|integer|min:0',
        ]);

        $production->update([
            'production_date' => $validated['production_date'],
            'cost_material' => $validated['cost_material'],
            'operational_cost' => $validated['operational_cost'],
            'notes' => $validated['notes'] ?? null,
        ]);

        $production->details()->delete();

        foreach ($validated['products'] as $p) {
            if ($p['quantity'] > 0) {
                ProductionDetail::create([
                    'production_id' => $production->id,
                    'product_id' => $p['product_id'],
                    'quantity' => $p['quantity'],
                ]);
            }
        }

        return redirect()->route('productions.index')->with('success', 'Produksi berhasil diperbarui.');
    }

    public function destroy(Production $production)
    {
        $production->details()->delete();
        $production->delete();

        return redirect()->route('productions.index')->with('success', 'Produksi berhasil dihapus.');
    }
}
