<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\Product;
use Illuminate\Http\Request;
use Carbon\Carbon;

class OrderController 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');
        $status    = $request->status;

        $query = Order::whereBetween('order_date', [$startDate, $endDate]);

        if ($status) {
            $query->where('status', $status);
        }

        $orders = $query->latest()->get();

        $headers = ['Tanggal', 'Customer', 'No Telp', 'Total Harga', 'Status', 'Aksi'];

        $rows = $orders->map(function ($order) {
            $statusLabel = ucfirst($order->status);

            if ($order->status === 'scheduled' && $order->pickup_date) {
                $statusLabel .= ' (' . $order->pickup_date->format('d/m/Y') . ')';
            }

            return [
                'cols' => [
                    $order->order_date ? $order->order_date->format('d F Y') : '-',
                    $order->customer_name,
                    $order->customer_phone ?? '-',
                    'Rp ' . number_format($order->total_price, 0, ',', '.'),
                    $statusLabel,
                ],
                'actions' => view('components.action-button', [
                    'id' => $order->id,
                    'resource' => 'orders',
                ])->render(),
            ];
        });

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

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

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

    public function store(Request $request)
    {
        $request->validate([
            'customer_name' => 'required|string|max:100',
            'customer_phone' => 'nullable|string|max:30',
            'status' => 'required|in:pending,completed,scheduled',
            'order_date' => 'required|date',
            'pickup_date' => 'required_if:status,scheduled|date|nullable',
            'products' => 'required|array',
            'products.*.qty' => 'required|integer|min:0',
        ]);

        $order = Order::create([
            'customer_name' => $request->customer_name,
            'customer_phone' => $request->customer_phone,
            'status' => $request->status,
            'order_date' => $request->order_date,
            'pickup_date' => $request->status === 'scheduled'
                ? $request->pickup_date
                : null,
            'total_price' => 0,
        ]);

        $total = 0;

        foreach ($request->products as $productId => $p) {
            if (isset($p['qty']) && $p['qty'] > 0) {
                $product = Product::findOrFail($productId);

                OrderDetail::create([
                    'order_id' => $order->id,
                    'product_id' => $product->id,
                    'qty' => $p['qty'],
                    'price' => $product->price,
                ]);

                $total += $p['qty'] * $product->price;
            }
        }

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

        return redirect()
            ->route('orders.index')
            ->with('success', 'Order berhasil ditambahkan.');
    }

    public function edit(Order $order)
    {
        $products = Product::where('available_for_reseller', true)
            ->orderBy('id')
            ->get();

        $order->load('details');

        return view('orders.edit', compact('order', 'products'));
    }

    public function update(Request $request, Order $order)
    {
        $request->validate([
            'customer_name' => 'required|string|max:100',
            'customer_phone' => 'nullable|string|max:30',
            'status' => 'required|in:pending,completed,scheduled',
            'order_date' => 'required|date',
            'pickup_date' => 'required_if:status,scheduled|nullable|date',
            'products' => 'required|array',
            'products.*.qty' => 'required|integer|min:0',
        ]);

        $order->update([
            'customer_name' => $request->customer_name,
            'customer_phone' => $request->customer_phone,
            'status' => $request->status,
            'order_date' => $request->order_date,
            'pickup_date' => $request->status === 'scheduled'
                ? $request->pickup_date
                : null,
        ]);

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

        $total = 0;

        foreach ($request->products as $productId => $p) {
            if (isset($p['qty']) && $p['qty'] > 0) {
                $product = Product::findOrFail($productId);

                OrderDetail::create([
                    'order_id' => $order->id,
                    'product_id' => $product->id,
                    'qty' => $p['qty'],
                    'price' => $product->price,
                ]);

                $total += $p['qty'] * $product->price;
            }
        }

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

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

    public function show(Order $order)
    {
        $order->load('details.product');

        return view('orders.show', compact('order'));
    }

    public function destroy(Order $order)
    {
        $order->details()->delete();
        $order->delete();

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