<?php

namespace App\Http\Controllers;

use App\Models\ResellerStock;
use App\Models\Reseller;
use App\Models\Product;
use Illuminate\Http\Request;

class ResellerStockController extends Controller
{
    public function resellerList()
    {
        $resellers = Reseller::all();
        return view('reseller_stocks.reseller_list', compact('resellers'));
    }

    public function showByReseller(Reseller $reseller)
    {
        $products = Product::where('available_for_reseller', true)->get();

        $stocks = ResellerStock::where('reseller_id', $reseller->id)
            ->orderBy('recorded_at', 'asc')
            ->get()
            ->groupBy(fn($s) => $s->recorded_at->format('Y-m-d'));

        return view('reseller_stocks.show_by_reseller', compact('reseller', 'products', 'stocks'));
    }

    public function index()
    {
        $resellers = Reseller::all();

        $headers = ['ID', 'Nama Reseller', 'Aksi'];

        $rows = $resellers->map(function($reseller) {
            return [
                'cols' => [
                    $reseller->id,
                    $reseller->name
                ],
                'actions' => '
                    <a href="' . route('reseller-stocks.show', $reseller->id) . '" 
                    class="btn-custom">
                        Lihat Stock
                    </a>
                '
            ];
        });

        return view('reseller_stocks.index', compact('headers', 'rows'));
    }

    public function show(Request $request, $resellerId)
    {
        $reseller = Reseller::findOrFail($resellerId);
        $products = Product::where('available_for_reseller', 1)->orderBy('id')->get();

        $startDate = $request->start_date ?? now()->subMonths(3)->format('Y-m-d');
        $endDate   = $request->end_date ?? now()->format('Y-m-d');

        $stocks = ResellerStock::where('reseller_id', $resellerId)
            ->whereDate('recorded_at', '>=', $startDate)
            ->whereDate('recorded_at', '<=', $endDate)
            ->orderBy('recorded_at')
            ->get()
            ->groupBy(fn($s) => $s->recorded_at->format('d F Y'));

        $rows = [];

        foreach ($stocks as $date => $items) {

            $cols = [];
            foreach ($products as $p) {
                $cols[$p->id] = '-';
            }

            foreach ($items as $i) {
                $cols[$i->product_id] = $i->stock;
            }

            $rows[] = [
                'date' => $date,
                'cols' => $cols
            ];
        }

        $rows = array_reverse($rows);

        $headers = ['Tanggal'];
        foreach ($products as $p) {
            $headers[] = $p->name;
        }

        $tableRows = [];
        foreach ($rows as $r) {

            $cols = [$r['date']];

            foreach ($products as $p) {
                $cols[] = $r['cols'][$p->id];
            }

            $tableRows[] = [
                'cols' => $cols
            ];
        }

        return view('reseller_stocks.show', compact(
            'reseller',
            'products',
            'tableRows',
            'headers',
            'startDate',
            'endDate'
        ));
    }

    public function edit($resellerId)
    {
        $reseller = Reseller::findOrFail($resellerId);

        $products = Product::where('available_for_reseller', 1)->get();

        $latestStockIds = ResellerStock::where('reseller_id', $resellerId)
            ->selectRaw('MAX(id) as id')
            ->groupBy('product_id')
            ->pluck('id');

        $currentStocks = ResellerStock::whereIn('id', $latestStockIds)
            ->get()
            ->keyBy('product_id');

        return view('reseller_stocks.edit', compact('reseller', 'products', 'currentStocks'));
    }

    public function update(Request $request, $resellerId)
    {
        $reseller = Reseller::findOrFail($resellerId);

        $request->validate([
            'stock' => 'required|array',
            'stock.*' => 'required|numeric|min:0',
        ]);

        $batchId = uniqid('batch_');

        $currentStocks = $reseller->stocks()
            ->latest('recorded_at')
            ->get()
            ->groupBy('product_id')
            ->map(fn($item) => $item->first()->stock);

        foreach ($request->stock as $productId => $newRemainingStock) {

            $oldStock = $currentStocks[$productId] ?? 0;

            if ($newRemainingStock > $oldStock) {
                return back()->withErrors([
                    "stock.$productId" => "Stok tidak boleh bertambah dari stok sebelumnya ($oldStock)"
                ]);
            }

            ResellerStock::create([
                'batch_id'     => $batchId,
                'reseller_id'  => $reseller->id,
                'product_id'   => $productId,
                'stock'        => $newRemainingStock,
                'recorded_at'  => now(),
            ]);
        }

        return redirect()->route('reseller-stocks.show', $reseller->id)
            ->with('success', 'Stok berhasil diperbarui.');
    }
}
