<?php

namespace App\Http\Controllers;

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

class SupplierController extends Controller
{
    public function index(Request $request)
    {
        $query = Supplier::query();
        
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('phone', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%")
                  ->orWhere('supplier_code', 'like', "%{$search}%");
            });
        }
        
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        
        $suppliers = $query->orderBy('name')->paginate(20);
        
        return view('suppliers.index', compact('suppliers'));
    }
    
    public function create()
    {
        return view('suppliers.create');
    }
    
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'required|string|max:50',
            'email' => 'nullable|email|max:100',
            'address' => 'nullable|string',
            'tax_number' => 'nullable|string|max:100',
            'opening_balance' => 'nullable|numeric|min:0',
            'credit_limit' => 'nullable|numeric|min:0',
        ]);
        
        DB::beginTransaction();
        
        try {
            // Generate supplier code
            $lastSupplier = Supplier::orderBy('id', 'desc')->first();
            $nextNumber = $lastSupplier ? intval(substr($lastSupplier->supplier_code, 4)) + 1 : 1;
            $supplierCode = 'SUP-' . str_pad($nextNumber, 3, '0', STR_PAD_LEFT);
            
            $supplier = Supplier::create([
                'supplier_code' => $supplierCode,
                'name' => $request->name,
                'company_name' => $request->company_name,
                'email' => $request->email,
                'phone' => $request->phone,
                'alternate_phone' => $request->alternate_phone,
                'tax_number' => $request->tax_number,
                'address' => $request->address,
                'city' => $request->city,
                'state' => $request->state,
                'postal_code' => $request->postal_code,
                'country' => $request->country,
                'contact_person' => $request->contact_person,
                'contact_person_phone' => $request->contact_person_phone,
                'website' => $request->website,
                'opening_balance' => $request->opening_balance ?? 0,
                'current_balance' => $request->opening_balance ?? 0,
                'credit_limit' => $request->credit_limit ?? 0,
                'payment_terms' => $request->payment_terms,
                'status' => $request->status ?? 'active',
                'notes' => $request->notes,
                'created_by' => auth()->id(),
            ]);
            
            DB::commit();
            
            return redirect()->route('suppliers.index')
                ->with('success', 'Supplier created successfully!');
                
        } catch (\Exception $e) {
            DB::rollBack();
            
            return redirect()->back()
                ->with('error', 'Failed to create supplier: ' . $e->getMessage())
                ->withInput();
        }
    }
    
    public function show(Supplier $supplier)
    {
        $supplier->load(['purchases' => function($query) {
            $query->latest()->limit(10);
        }, 'purchases.items']);
        
        // Calculate summary
        $summary = [
            'total_purchases' => $supplier->purchases()->count(),
            'total_amount' => $supplier->purchases()->sum('grand_total'),
            'total_paid' => $supplier->purchases()->sum('paid_amount'),
            'total_due' => $supplier->purchases()->sum('due_amount'),
            'last_purchase' => $supplier->purchases()->latest()->first(),
        ];
        
        return view('suppliers.show', compact('supplier', 'summary'));
    }
    
    public function edit(Supplier $supplier)
    {
        return view('suppliers.edit', compact('supplier'));
    }
    
    public function update(Request $request, Supplier $supplier)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'required|string|max:50',
            'email' => 'nullable|email|max:100',
            'address' => 'nullable|string',
            'tax_number' => 'nullable|string|max:100',
            'opening_balance' => 'nullable|numeric|min:0',
            'credit_limit' => 'nullable|numeric|min:0',
        ]);
        
        $supplier->update([
            'name' => $request->name,
            'company_name' => $request->company_name,
            'email' => $request->email,
            'phone' => $request->phone,
            'alternate_phone' => $request->alternate_phone,
            'tax_number' => $request->tax_number,
            'address' => $request->address,
            'city' => $request->city,
            'state' => $request->state,
            'postal_code' => $request->postal_code,
            'country' => $request->country,
            'contact_person' => $request->contact_person,
            'contact_person_phone' => $request->contact_person_phone,
            'website' => $request->website,
            'opening_balance' => $request->opening_balance ?? 0,
            'credit_limit' => $request->credit_limit ?? 0,
            'payment_terms' => $request->payment_terms,
            'status' => $request->status ?? 'active',
            'notes' => $request->notes,
            'updated_by' => auth()->id(),
        ]);
        
        return redirect()->route('suppliers.show', $supplier)
            ->with('success', 'Supplier updated successfully!');
    }
    
    public function destroy(Supplier $supplier)
    {
        if ($supplier->purchases()->exists()) {
            return redirect()->back()
                ->with('error', 'Cannot delete supplier with existing purchases!');
        }
        
        $supplier->delete();
        
        return redirect()->route('suppliers.index')
            ->with('success', 'Supplier deleted successfully!');
    }
    
    public function updateBalance(Request $request, Supplier $supplier)
    {
        $request->validate([
            'amount' => 'required|numeric|min:0',
            'type' => 'required|in:add,subtract',
            'note' => 'nullable|string',
        ]);
        
        DB::beginTransaction();
        
        try {
            if ($request->type == 'add') {
                $supplier->current_balance += $request->amount;
            } else {
                $supplier->current_balance -= $request->amount;
            }
            
            $supplier->save();
            
            // You can create a transaction log here
            
            DB::commit();
            
            return redirect()->back()
                ->with('success', 'Supplier balance updated successfully!');
                
        } catch (\Exception $e) {
            DB::rollBack();
            
            return redirect()->back()
                ->with('error', 'Failed to update balance: ' . $e->getMessage());
        }
    }
}