<?php

namespace App\Http\Controllers\Accounting;

use App\Http\Controllers\Controller;
use App\Models\Supplier;
use App\Models\FinancialTreasury;
use App\Models\FinancialCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SupplierController extends Controller
{
    public function index()
    {
        $suppliers = Supplier::where('is_active', true)->latest()->paginate(20);
        return view('accounting.suppliers.index', compact('suppliers'));
    }

    public function show(Supplier $supplier)
    {
        $bills = $supplier->bills()->latest()->paginate(10, ['*'], 'bills_page');
        $transactions = $supplier->transactions()->latest()->paginate(10, ['*'], 'trans_page');
        $treasuries = FinancialTreasury::where('is_active', true)->get();

        return view('accounting.suppliers.show', compact('supplier', 'bills', 'transactions', 'treasuries'));
    }

    public function create()
    {
        $currencies = \App\Models\Currency::where('is_active', true)->get();
        return view('accounting.suppliers.create', compact('currencies'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'nullable|email',
            'phone' => 'nullable|string',
            'tax_id' => 'nullable|string',
            'address' => 'nullable|string',
            'currency_id' => 'nullable|exists:currencies,id',
            'opening_balance' => 'nullable|numeric',
        ]);

        Supplier::create($validated);
        return redirect()->route('accounting.suppliers.index')->with('success', 'Supplier created successfully.');
    }

    public function edit(Supplier $supplier)
    {
        $currencies = \App\Models\Currency::where('is_active', true)->get();
        return view('accounting.suppliers.edit', compact('supplier', 'currencies'));
    }

    public function update(Request $request, Supplier $supplier)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'nullable|email',
            'phone' => 'nullable|string',
            'tax_id' => 'nullable|string',
            'address' => 'nullable|string',
            'currency_id' => 'nullable|exists:currencies,id',
            'opening_balance' => 'nullable|numeric',
        ]);

        $supplier->update($validated);
        return redirect()->route('accounting.suppliers.index')->with('success', 'Supplier updated successfully.');
    }

    public function destroy(Supplier $supplier)
    {
        $supplier->update(['is_active' => false]);
        return back()->with('success', 'Supplier deactivated successfully.');
    }

    public function addPayment(Request $request, Supplier $supplier)
    {
        $request->validate([
            'amount' => 'required|numeric|min:0.01',
            'treasury_id' => 'required|exists:financial_treasuries,id',
            'date' => 'required|date',
            'description' => 'nullable|string',
        ]);

        try {
            DB::transaction(function () use ($request, $supplier) {
                $treasury = FinancialTreasury::find($request->treasury_id);

                // Check treasury balance
                if ($treasury->balance < $request->amount) {
                    throw new \Exception('Insufficient treasury balance.');
                }

                // Create Financial Transaction
                $transaction = $supplier->transactions()->create([
                    'treasury_id' => $request->treasury_id,
                    'currency_id' => $supplier->currency_id ?? \App\Models\Currency::getBase()->id,
                    'amount' => $request->amount,
                    'type' => 'expense', // Paying to supplier is an expense
                    'date' => $request->date,
                    'description' => $request->description ?? 'Advance payment to supplier: ' . $supplier->name,
                    'user_id' => auth()->id(),
                ]);

                // Update Treasury
                $treasury->decrement('balance', $request->amount);

                // Update Supplier Balance (Advance Credit)
                $supplier->increment('balance', $request->amount);
            });

            return back()->with('success', 'Payment recorded successfully.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }
}
