<?php

namespace App\Services;

use App\Models\Purchase;
use App\Models\PurchaseItem;
use App\Models\Product;
use Illuminate\Support\Facades\DB;

class PurchaseService
{
    public function __construct(
        protected ProductService $productService
    ) {}

    public function create(array $data): Purchase
    {
        return DB::transaction(function () use ($data) {
            $total = $data['total'];

            $purchase = Purchase::create([
                'purchase_number' => $this->generatePurchaseNumber(),
                'supplier_id'    => $data['supplier_id'],
                'user_id'        => $data['user_id'],
                'purchase_date'  => $data['purchase_date'] ?? now(),
                'status'         => 'pending',
                'payment_status' => 'unpaid',
                'subtotal'       => $data['subtotal'],
                'tax'            => $data['tax'] ?? 0,
                'discount'       => $data['discount'] ?? 0,
                'total'          => $total,
                'amount_paid'    => 0,
                'amount_due'     => $total,
                'notes'          => $data['notes'] ?? null,
                'branch_id'      => $data['branch_id'] ?? current_branch_id(),
            ]);

            // Create purchase items
            foreach ($data['items'] as $item) {
                PurchaseItem::create([
                    'purchase_id' => $purchase->id,
                    'product_id' => $item['product_id'],
                    'quantity' => $item['quantity'],
                    'unit_cost' => $item['unit_cost'],
                    'subtotal' => $item['subtotal'],
                    'branch_id' => $purchase->branch_id,
                ]);
            }

            return $purchase->load('items.product', 'supplier');
        });
    }

    public function receive(Purchase $purchase): Purchase
    {
        if ($purchase->status !== 'pending') {
            throw new \Exception('Only pending purchases can be received.');
        }

        return DB::transaction(function () use ($purchase) {
            // Eager-load items with their products to avoid lazy loading
            $purchase->load('items.product');

            // Update stock for each item (branch-aware)
            foreach ($purchase->items as $item) {
                $this->productService->incrementStock(
                    $item->product,
                    $item->quantity,
                    $purchase->branch_id  // pass the purchase's branch explicitly
                );

                // Update product cost price
                $item->product->update([
                    'cost_price' => $item->unit_cost,
                ]);
            }

            $purchase->update(['status' => 'received']);

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

    protected function generatePurchaseNumber(): string
    {
        $prefix = 'PO';
        $date = now()->format('Ymd');
        $count = Purchase::whereDate('created_at', today())->count() + 1;
        $number = str_pad($count, 4, '0', STR_PAD_LEFT);
        
        return $prefix . $date . $number;
    }
}
