<?php

namespace App\Http\Controllers;

use App\Models\Reseller;
use App\Models\Product;
use App\Models\ResellerBarter;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ResellerBarterController extends Controller
{
    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-barters.show', $reseller->id) . '" class="btn-custom">Lihat Barter</a>',
            ];
        });

        return view('reseller_barters.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()->subMonth(3)->format('Y-m-d');
        $endDate   = $request->end_date ?? now()->format('Y-m-d');

        $barters = ResellerBarter::where('reseller_id', $resellerId)
            ->whereDate('date', '>=', $startDate)
            ->whereDate('date', '<=', $endDate)
            ->orderBy('date')
            ->get()
            ->groupBy('batch_id');

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

        $tableRows = [];

        foreach ($barters as $batchId => $items) {

            $date = $items->first()->date->format('d F Y');

            $qtyMap = [];
            foreach ($products as $product) {
                $qtyMap[$product->id] = 0;
            }

            foreach ($items as $item) {
                $qtyMap[$item->product_id] = $item->qty;
            }

            $cols = [$date];
            foreach ($products as $product) {
                $cols[] = $qtyMap[$product->id];
            }

            $editUrl   = route('reseller-barters.edit', $batchId);
            $deleteUrl = route('reseller-barters.destroy', $batchId);

            $actions = '
                <div class="d-flex align-items-center gap-1">
                    <a href="'.$editUrl.'"
                        class="btn px-2 py-1"
                        style="background-color:#d4af37;color:#ffffff;border-radius:6px;">
                        <i class="bi bi-pen"></i>
                    </a>

                    <form method="POST" action="'.$deleteUrl.'" class="d-inline">
                        '.csrf_field().method_field('DELETE').'
                        <button type="submit"
                            class="btn px-2 py-1"
                            style="background-color:#8c2b25;color:#ffffff;border-radius:6px;"
                            onclick="return confirm(\'Yakin ingin menghapus data barter ini?\')">
                            <i class="bi bi-trash"></i>
                        </button>
                    </form>
                </div>
            ';

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

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

    public function create($resellerId)
    {
        $reseller = Reseller::findOrFail($resellerId);
        $products = Product::where('available_for_reseller', 1)->orderBy('id')->get();
        return view('reseller_barters.create', compact('reseller', 'products'));
    }

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

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

        $selectedProducts = collect($request->products)
            ->filter(fn($qty) => intval($qty) > 0);

        if ($selectedProducts->isEmpty()) {
            return back()->withErrors(['products' => 'Isi minimal 1 produk dengan qty > 0']);
        }

        $batchId = uniqid('batch_');

        DB::transaction(function () use ($reseller, $request, $selectedProducts, $batchId) {
            foreach ($selectedProducts as $productId => $qty) {
                ResellerBarter::create([
                    'reseller_id' => $reseller->id,
                    'product_id'  => $productId,
                    'qty'         => intval($qty),
                    'date'        => $request->date,
                    'batch_id'    => $batchId,
                ]);
            }
        });

        return redirect()->route('reseller-barters.show', $reseller->id)
            ->with('success', 'Data barter berhasil ditambahkan.');
    }

    public function edit($batchId)
    {
        $barters = ResellerBarter::where('batch_id', $batchId)->get();
        if ($barters->isEmpty()) abort(404);

        $reseller = $barters->first()->reseller;
        $products = Product::where('available_for_reseller', 1)->orderBy('id')->get();

        $barterData = [];
        foreach ($barters as $b) {
            $barterData[$b->product_id] = $b->qty;
        }
        $barterData['date'] = $barters->first()->date->format('Y-m-d');

        return view('reseller_barters.edit', compact('reseller', 'products', 'barterData', 'batchId'));
    }

    public function update(Request $request, $batchId)
    {
        $barters = ResellerBarter::where('batch_id', $batchId)->get();
        if ($barters->isEmpty()) abort(404);

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

        $selectedProducts = collect($request->products)
            ->filter(fn($qty) => intval($qty) > 0);

        if ($selectedProducts->isEmpty()) {
            return back()->withErrors(['products' => 'Isi minimal 1 produk dengan qty > 0']);
        }

        $resellerId = $barters->first()->reseller_id;

        DB::transaction(function () use ($selectedProducts, $request, $batchId, $resellerId) {
            ResellerBarter::where('batch_id', $batchId)->delete();

            foreach ($selectedProducts as $productId => $qty) {
                ResellerBarter::create([
                    'reseller_id' => $resellerId,
                    'product_id'  => $productId,
                    'qty'         => intval($qty),
                    'date'        => $request->date,
                    'batch_id'    => $batchId,
                ]);
            }
        });

        return redirect()->route('reseller-barters.show', $resellerId)
            ->with('success', 'Data barter berhasil diperbarui.');
    }

    public function destroy($batchId)
    {
        $barters = ResellerBarter::where('batch_id', $batchId)->get();
        if ($barters->isEmpty()) abort(404);

        $resellerId = $barters->first()->reseller_id;
        $barters->each->delete();

        return redirect()->route('reseller-barters.show', $resellerId)
            ->with('success', 'Barter berhasil dihapus.');
    }
}
