<?php

namespace App\Http\Controllers;

use App\Models\ResellerOrder;
use App\Models\ResellerOrderDetail;
use App\Models\ResellerStock;
use App\Models\ResellerPayment;
use App\Models\Reseller;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class ResellerOrderController 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');

        $orders = ResellerOrder::with('reseller')
            ->whereBetween('order_date', [$startDate, $endDate])
            ->orderBy('order_date', 'desc')
            ->get();

        $headers = ['Tanggal Order', 'No. Nota', 'Reseller', 'Total', 'Aksi'];

        $rows = $orders->map(function ($o) {
            return [
                'cols' => [
                    $o->order_date->format('d F Y'),
                    $o->invoice_number ?? '-',
                    $o->reseller->name ?? '-',
                    'Rp ' . number_format($o->total, 0, ',', '.')
                ],
                'actions' => view('components.action-button', [
                    'id' => $o->id,
                    'resource' => 'reseller-orders'
                ])->render(),
            ];
        });

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

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

        return view('reseller_orders.create', compact('resellers', 'products'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'reseller_id' => 'required|exists:resellers,id',
            'order_date' => 'required|date',
            'invoice_number' => 'nullable|string|max:255',
            'products' => 'required|array',
            'products.*.qty' => 'required|integer|min:0',
        ]);

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

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

        DB::transaction(function () use ($request, $selectedProducts) {
            $order = ResellerOrder::create([
                'reseller_id' => $request->reseller_id,
                'order_date' => $request->order_date,
                'invoice_number' => $request->invoice_number ?? null,
                'total' => 0,
            ]);

            $total = 0;

            foreach ($selectedProducts as $productId => $p) {
                $product = Product::findOrFail($productId);
                $qty = intval($p['qty']);
                $price = $product->reseller_price ?? $product->price;

                ResellerOrderDetail::create([
                    'reseller_order_id' => $order->id,
                    'product_id' => $productId,
                    'qty' => $qty,
                    'price' => $price,
                ]);

                $total += $qty * $price;

                ResellerStock::create([
                    'reseller_id' => $order->reseller_id,
                    'product_id' => $productId,
                    'stock' => $qty,
                    'recorded_at' => $request->order_date,
                ]);
            }

            $order->update(['total' => $total]);

            ResellerPayment::create([
                'reseller_id' => $order->reseller_id,
                'reseller_order_id' => $order->id,
                'amount_due' => $total,
                'amount_paid' => 0,
                'status' => 'pending',
            ]);
        });

        return redirect()->route('reseller-orders.index')->with('success', 'Reseller order created successfully');
    }

    public function edit(ResellerOrder $resellerOrder)
    {
        $resellerOrder->load('details');
        $resellers = Reseller::all();
        $products = Product::where('available_for_reseller', true)->get();

        return view('reseller_orders.edit', compact('resellerOrder', 'resellers', 'products'));
    }

    public function update(Request $request, ResellerOrder $resellerOrder)
    {
        $request->validate([
            'reseller_id' => 'required|exists:resellers,id',
            'order_date' => 'required|date',
            'invoice_number' => 'nullable|string|max:255',
            'products' => 'required|array',
            'products.*.qty' => 'required|integer|min:0',
        ]);

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

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

        DB::transaction(function () use ($request, $selectedProducts, $resellerOrder) {

            $resellerOrder->update([
                'reseller_id' => $request->reseller_id,
                'order_date' => $request->order_date,
                'invoice_number' => $request->invoice_number ?? null,
            ]);

            $resellerOrder->details()->delete();
            $total = 0;

            foreach ($selectedProducts as $productId => $p) {
                $product = Product::findOrFail($productId);
                $qty = intval($p['qty']);
                $price = $product->reseller_price ?? $product->price;

                ResellerOrderDetail::create([
                    'reseller_order_id' => $resellerOrder->id,
                    'product_id' => $productId,
                    'qty' => $qty,
                    'price' => $price,
                ]);

                $total += $qty * $price;

                ResellerStock::create([
                    'reseller_id' => $resellerOrder->reseller_id,
                    'product_id' => $productId,
                    'stock' => $qty,
                    'recorded_at' => $request->order_date,
                ]);
            }

            $resellerOrder->update(['total' => $total]);

            $payment = ResellerPayment::where('reseller_id', $resellerOrder->reseller_id)
                ->where('reseller_order_id', $resellerOrder->id)
                ->first();

            if ($payment) {
                $payment->update([
                    'amount_due' => $total,
                    'status' => $payment->amount_paid >= $total ? 'paid' : 'pending',
                ]);
            }
        });

        return redirect()->route('reseller-orders.index')->with('success', 'Reseller order updated successfully');
    }

    public function show(ResellerOrder $resellerOrder)
    {
        $resellerOrder->load('details.product', 'reseller');
        return view('reseller_orders.show', compact('resellerOrder'));
    }

    public function destroy(ResellerOrder $resellerOrder)
    {
        $resellerOrder->delete();
        return redirect()->route('reseller-orders.index')->with('success', 'Reseller order deleted successfully');
    }
}
