<?php

namespace App\Http\Controllers;

use App\Models\Purchase;
use App\Models\PurchaseDetail;
use App\Models\Medicine;
use App\Models\Supplier;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PurchaseController extends Controller
{
    public function index()
    {
        $purchases = Purchase::with(['supplier', 'user'])->latest()->get();
        return view('transactions.purchases.index', compact('purchases'));
    }

    public function create()
    {
        $suppliers = Supplier::all();
        $medicines = Medicine::all();
        return view('transactions.purchases.create', compact('suppliers', 'medicines'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'supplier_id' => 'required|exists:suppliers,id',
            'date' => 'required|date',
            'medicine_id' => 'required|array|min:1',
            'medicine_id.*' => 'required|exists:medicines,id',
            'qty' => 'required|array|min:1',
            'qty.*' => 'required|integer|min:1',
            'purchase_price' => 'required|array|min:1',
            'purchase_price.*' => 'required|numeric|min:0',
            'batch_number' => 'nullable|array',
            'expired_date' => 'required|array|min:1',
            'expired_date.*' => 'required|date',
        ]);

        try {
            DB::beginTransaction();

            $total_amount = 0;
            $purchase = Purchase::create([
                'user_id' => auth()->id(),
                'supplier_id' => $request->supplier_id,
                'date' => $request->date,
                'total_amount' => 0
            ]);

            foreach($request->medicine_id as $key => $med_id) {
                $qty = $request->qty[$key];
                $price = $request->purchase_price[$key];
                $subtotal = $qty * $price;
                $total_amount += $subtotal;

                PurchaseDetail::create([
                    'purchase_id' => $purchase->id,
                    'medicine_id' => $med_id,
                    'qty' => $qty,
                    'batch_number' => $request->batch_number[$key] ?? null,
                    'expired_date' => $request->expired_date[$key],
                    'purchase_price' => $price,
                    'subtotal' => $subtotal
                ]);

                // Update Medicine Stock and Price
                $medicine = Medicine::find($med_id);
                $medicine->increment('current_stock', $qty);
                $medicine->update(['purchase_price' => $price]);
            }

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

            DB::commit();
            return redirect()->route('purchases.index')->with('success', 'Transaksi pembelian berhasil disimpan dan stok telah diperbarui.');

        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->back()->withErrors(['error' => 'Gagal menyimpan transaksi: ' . $e->getMessage()]);
        }
    }

    public function show(Purchase $purchase)
    {
        $purchase->load(['supplier', 'user', 'details.medicine.unit']);
        return view('transactions.purchases.show', compact('purchase'));
    }

    public function edit(Purchase $purchase)
    {
        $purchase->load('details');
        $suppliers = Supplier::all();
        $medicines = Medicine::all();
        
        $purchaseDetails = $purchase->details->map(function($d) { 
            return [
                'id' => $d->id, 
                'medicine_id' => $d->medicine_id, 
                'qty' => $d->qty, 
                'price' => $d->purchase_price, 
                'batch_number' => $d->batch_number, 
                'expired_date' => $d->expired_date
            ]; 
        });

        return view('transactions.purchases.edit', compact('purchase', 'suppliers', 'medicines', 'purchaseDetails'));
    }

    public function update(Request $request, Purchase $purchase)
    {
        $request->validate([
            'supplier_id' => 'required|exists:suppliers,id',
            'date' => 'required|date',
            'medicine_id' => 'required|array|min:1',
            'medicine_id.*' => 'required|exists:medicines,id',
            'qty' => 'required|array|min:1',
            'qty.*' => 'required|integer|min:1',
            'purchase_price' => 'required|array|min:1',
            'purchase_price.*' => 'required|numeric|min:0',
            'batch_number' => 'nullable|array',
            'expired_date' => 'required|array|min:1',
            'expired_date.*' => 'required|date',
        ]);

        try {
            DB::beginTransaction();

            // 1. Rollback stok lama
            foreach ($purchase->details as $oldDetail) {
                $medicine = Medicine::find($oldDetail->medicine_id);
                if ($medicine) {
                    $medicine->decrement('current_stock', $oldDetail->qty);
                }
            }

            // 2. Hapus detail lama
            $purchase->details()->delete();

            // 3. Update master pembelian
            $total_amount = 0;
            $purchase->update([
                'supplier_id' => $request->supplier_id,
                'date' => $request->date,
            ]);

            // 4. Masukkan detail baru & update stok baru
            foreach($request->medicine_id as $key => $med_id) {
                $qty = $request->qty[$key];
                $price = $request->purchase_price[$key];
                $subtotal = $qty * $price;
                $total_amount += $subtotal;

                PurchaseDetail::create([
                    'purchase_id' => $purchase->id,
                    'medicine_id' => $med_id,
                    'qty' => $qty,
                    'batch_number' => $request->batch_number[$key] ?? null,
                    'expired_date' => $request->expired_date[$key],
                    'purchase_price' => $price,
                    'subtotal' => $subtotal
                ]);

                $medicine = Medicine::find($med_id);
                $medicine->increment('current_stock', $qty);
                $medicine->update(['purchase_price' => $price]);
            }

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

            DB::commit();
            return redirect()->route('purchases.index')->with('success', 'Transaksi pembelian berhasil diperbarui dan stok telah disesuaikan.');

        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->back()->withErrors(['error' => 'Gagal memperbarui transaksi: ' . $e->getMessage()]);
        }
    }

    public function destroy(Purchase $purchase)
    {
        try {
            DB::beginTransaction();

            // Rollback stok
            foreach ($purchase->details as $detail) {
                $medicine = Medicine::find($detail->medicine_id);
                if ($medicine) {
                    $medicine->decrement('current_stock', $detail->qty);
                }
            }

            $purchase->delete(); // Akan menghapus purchase_details juga karena cascade

            DB::commit();
            return redirect()->route('purchases.index')->with('success', 'Transaksi pembelian berhasil dihapus dan stok telah dikembalikan.');

        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->route('purchases.index')->withErrors(['error' => 'Gagal menghapus transaksi: ' . $e->getMessage()]);
        }
    }
}
