<?php

namespace App\Modules\TakingOrder\Services;

use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\VisitPlan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class OrderService
{

    /**
     * Update existing order dengan items tambahan
     */
    public function updateOrder(Order $order, array $items): Order
    {
        return DB::transaction(function () use ($order, $items) {
            $totalAdditional = 0;

            foreach ($items as $item) {
                $product = Product::findOrFail($item['product_id']);

                // Ambil data dari request
                $qty = $item['qty'];
                $qtySatuan = $item['qty_satuan'] ?? $qty;
                $price = $item['price'] ?? ($product->price * $qty);
                $hargaSatuan = $item['harga_satuan'] ?? $product->price;
                $unitType = $item['unit_type'] ?? 'bulk';
                $unitName = $item['unit_name'] ?? ($unitType === 'retail' ? $product->retail_unit : $product->bulk_unit);

                // Cek apakah item sudah ada di order
                $existingItem = OrderItem::where('order_id', $order->id)
                    ->where('product_id', $item['product_id'])
                    ->first();

                if ($existingItem) {
                    // Update quantity
                    $newQty = $existingItem->qty + $qty;
                    $existingItem->update([
                        'qty' => $newQty,
                        'qty_satuan' => $qtySatuan,
                        'price' => $price,
                        'harga_satuan' => $hargaSatuan,
                        'unit_type' => $unitType,
                        'unit_name' => $unitName,
                    ]);
                    $subtotal = $price;
                } else {
                    // Tambah item baru
                    OrderItem::create([
                        'order_id' => $order->id,
                        'product_id' => $item['product_id'],
                        'qty' => $qty,
                        'qty_satuan' => $qtySatuan,
                        'price' => $price,
                        'harga_satuan' => $hargaSatuan,
                        'unit_type' => $unitType,
                        'unit_name' => $unitName,
                    ]);
                    $subtotal = $price;
                }

                // Kurangi stock
                $product->decrement('stock', $qty);
                $totalAdditional += $subtotal;
            }

            // Update total order
            $order->increment('total_amount', $totalAdditional);

            Log::info('Order updated', [
                'order_id' => $order->id,
                'additional_items' => count($items),
                'additional_amount' => $totalAdditional
            ]);

            return $order->fresh();
        });
    }

    /**
     * Membuat order baru dengan status pending
     */
    public function createOrder(int $userId, int $customerId, array $items, ?string $notes = null): Order
    {
        return DB::transaction(function () use ($userId, $customerId, $items, $notes) {
            $totalAmount = 0;
            $orderItems = [];

            foreach ($items as $item) {
                $product = Product::findOrFail($item['product_id']);

                $qty = $item['qty'];

                // ⚠️ PASTIKAN: harga_satuan sesuai dengan unit yang dipilih
                $unitType = $item['unit_type'] ?? 'bulk';
                $hargaSatuan = $item['harga_satuan'] ?? $product->price;

                // ⚠️ PASTIKAN: subtotal = harga_satuan × qty
                $subtotal = $hargaSatuan * $qty;
                $totalAmount += $subtotal;

                $orderItems[] = [
                    'product_id' => $item['product_id'],
                    'qty' => $qty,
                    'qty_satuan' => $item['qty_satuan'] ?? $qty,
                    'price' => $subtotal, // total per item (harga_satuan × qty)
                    'harga_satuan' => $hargaSatuan,
                    'unit_type' => $unitType,
                    'unit_name' => $item['unit_name'] ?? ($unitType === 'retail' ? 'pcs' : 'Karton'),
                ];

                // Kurangi stock (stock selalu dalam satuan bulk)
                $product->decrement('stock', $qty);
            }

            $order = Order::create([
                'user_id' => $userId,
                'customer_id' => $customerId,
                'invoice_code' => 'INV/' . date('Ymd') . '/' . strtoupper(uniqid()),
                'total_amount' => $totalAmount,
                'notes' => $notes,
                'status' => 'pending',
            ]);

            foreach ($orderItems as $item) {
                OrderItem::create([
                    'order_id' => $order->id,
                    'product_id' => $item['product_id'],
                    'qty' => $item['qty'],
                    'qty_satuan' => $item['qty_satuan'],
                    'price' => $item['price'],
                    'harga_satuan' => $item['harga_satuan'],
                    'unit_type' => $item['unit_type'],
                    'unit_name' => $item['unit_name'],
                ]);
            }

            Log::info('Order created', [
                'order_id' => $order->id,
                'invoice_code' => $order->invoice_code,
                'user_id' => $userId,
                'customer_id' => $customerId,
                'total_amount' => $totalAmount,
                'items' => $orderItems
            ]);

            return $order;
        });
    }

    /**
     * Memproses order (ubah status menjadi processed)
     */
    public function processOrder(Order $order): bool
    {
        return DB::transaction(function () use ($order) {
            // Ubah status order
            $order->update(['status' => 'processed']);

            // Update visit plan menjadi done (opsional)
            VisitPlan::where('user_id', $order->user_id)
                ->where('customer_id', $order->customer_id)
                ->where('visit_date', now()->toDateString())
                ->update(['status' => 'done']);

            Log::info('Order processed', [
                'order_id' => $order->id,
                'invoice_code' => $order->invoice_code,
                'user_id' => $order->user_id
            ]);

            return true;
        });
    }
}
