<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SupplierPurchase;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Toastr;

class SupplierPurchaseController extends Controller
{
    /**
     * Display a listing of supplier purchases
     */
    public function index(Request $request)
    {
        $query = SupplierPurchase::query();
        
        // Search functionality
        if ($request->has('keyword') && $request->keyword) {
            $keyword = $request->keyword;
            $query->where('supplier_name', 'like', '%' . $keyword . '%')
                  ->orWhere('product_name', 'like', '%' . $keyword . '%');
        }
        
        // Date filter
        if ($request->has('start_date') && $request->start_date) {
            $query->whereDate('purchase_date', '>=', $request->start_date);
        }
        
        if ($request->has('end_date') && $request->end_date) {
            $query->whereDate('purchase_date', '<=', $request->end_date);
        }
        
        $data = $query->orderBy('purchase_date', 'DESC')->paginate(15);
        
        // Dashboard statistics
        $totalPurchases = SupplierPurchase::getTotalPurchases();
        $currentMonth = Carbon::now();
        $monthlyTotal = SupplierPurchase::getMonthlyTotal($currentMonth->year, $currentMonth->month);
        $recentPurchases = SupplierPurchase::getRecentPurchases(5);
        
        return view('backEnd.supplier_purchase.index', compact('data', 'totalPurchases', 'monthlyTotal', 'recentPurchases'));
    }

    /**
     * Show the form for creating a new supplier purchase
     */
    public function create()
    {
        return view('backEnd.supplier_purchase.create');
    }

    /**
     * Store a newly created supplier purchase in database
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'supplier_name' => 'required|string|max:255',
            'product_name' => 'required|string|max:255',
            'quantity' => 'required|numeric|min:1',
            'unit_price' => 'required|numeric|min:0.01',
            'purchase_date' => 'required|date',
            'notes' => 'nullable|string',
        ], [
            'supplier_name.required' => 'Supplier name is required',
            'product_name.required' => 'Product name is required',
            'quantity.required' => 'Quantity is required',
            'quantity.numeric' => 'Quantity must be a number',
            'unit_price.required' => 'Unit price is required',
            'purchase_date.required' => 'Purchase date is required',
        ]);

        $input = $request->all();
        $input['total_price'] = $request->quantity * $request->unit_price;
        
        SupplierPurchase::create($input);
        
        Toastr::success('Success', 'Supplier purchase record added successfully');
        return redirect()->route('supplier-purchases.index');
    }

    /**
     * Show the form for editing a supplier purchase
     */
    public function edit($id)
    {
        $purchase = SupplierPurchase::find($id);
        
        if (!$purchase) {
            Toastr::error('Error', 'Purchase record not found');
            return redirect()->route('supplier-purchases.index');
        }
        
        return view('backEnd.supplier_purchase.edit', compact('purchase'));
    }

    /**
     * Update the specified supplier purchase in database
     */
    public function update(Request $request)
    {
        $this->validate($request, [
            'supplier_name' => 'required|string|max:255',
            'product_name' => 'required|string|max:255',
            'quantity' => 'required|numeric|min:1',
            'unit_price' => 'required|numeric|min:0.01',
            'purchase_date' => 'required|date',
            'notes' => 'nullable|string',
        ]);

        $purchase = SupplierPurchase::find($request->id);
        
        if (!$purchase) {
            Toastr::error('Error', 'Purchase record not found');
            return redirect()->route('supplier-purchases.index');
        }
        
        $input = $request->all();
        $input['total_price'] = $request->quantity * $request->unit_price;
        
        $purchase->update($input);
        
        Toastr::success('Success', 'Purchase record updated successfully');
        return redirect()->route('supplier-purchases.index');
    }

    /**
     * Delete the specified supplier purchase
     */
    public function destroy(Request $request)
    {
        $purchase = SupplierPurchase::find($request->id);
        
        if (!$purchase) {
            Toastr::error('Error', 'Purchase record not found');
            return redirect()->route('supplier-purchases.index');
        }
        
        $purchase->delete();
        
        Toastr::success('Success', 'Purchase record deleted successfully');
        return redirect()->route('supplier-purchases.index');
    }

    /**
     * Get monthly summary
     */
    public function monthlySummary(Request $request)
    {
        $year = $request->input('year', Carbon::now()->year);
        $month = $request->input('month', Carbon::now()->month);
        
        $data = SupplierPurchase::whereYear('purchase_date', $year)
                                ->whereMonth('purchase_date', $month)
                                ->orderBy('purchase_date', 'DESC')
                                ->get();
        
        $monthlyTotal = SupplierPurchase::getMonthlyTotal($year, $month);
        
        return view('backEnd.supplier_purchase.monthly_summary', compact('data', 'monthlyTotal', 'year', 'month'));
    }
}
