<?php

namespace App\Http\Controllers;

use App\Models\ProductDetailsModel;
use App\Models\ProductModel;
use App\Models\SupplierModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SuppliersController extends Controller
{

    public function index()
    {
        $suppliers = SupplierModel::where('branch_id', session('branch_id'))->orderBy('id', 'desc')->get();

        return view('suppliers.index', compact('suppliers'));
    }

    public function add()
    {
        return view('suppliers.add');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required',
            'phone_Number' => 'required',
            'email' => 'nullable|email|unique:supplier,email',
            'address' => 'nullable',
            'isActive' => 'nullable|boolean',
        ]);

        DB::beginTransaction();

        try {
            SupplierModel::create([
                'branch_id' => session('branch_id'),
                'supplier_name' => $validated['name'],
                'phone' => $validated['phone_Number'],
                'email' => $validated['email'],
                'address' => $validated['address'],
                'active_status' => $validated['isActive'] ?? 0,
            ]);

            DB::commit();

            return redirect()->route('supplier-index')->with('success', 'Supplier added successfully');

        } catch (\Exception $e) {

            DB::rollBack();

            \Log::info('While Storing Suppliers' . $e->getMessage());

            return back()->with('error', 'Failed to add Supplier, Please try again.');
        }
    }

    public function edit($id)
    {
        $supplier = SupplierModel::findOrFail($id);
        return view('suppliers.edit', compact('supplier'));
    }

    public function update(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required',
            'phone_Number' => 'required',
            'email' => 'nullable|email|unique:supplier,email,' . $request->id,
            'address' => 'nullable',
            'isActive' => 'nullable|boolean',
        ]);

        DB::beginTransaction();

        try {
            $supplier = SupplierModel::findOrFail($request->id);

            $supplier->update([
                'supplier_name' => $validated['name'],
                'phone' => $validated['phone_Number'],
                'email' => $validated['email'],
                'address' => $validated['address'],
                'active_status' => $validated['isActive'] ?? 0,
            ]);

            DB::commit();

            return redirect()->route('supplier-index')->with('success', 'Supplier updated successfully');

        } catch (\Exception $e) {

            DB::rollBack();

            \Log::info('While Updating Suppliers' . $e->getMessage());

            return back()->with('error', 'Failed to update Supplier, Please try again.');
        }
    }

    public function delete($id)
    {
        $supplier = SupplierModel::findOrFail($id);

        $hasActiveProducts = ProductModel::where('supplier_id', $supplier->id)
            ->where('active_flag', 'A')
            ->exists();
        $hasActiveDetails = ProductDetailsModel::where('supplier_id', $supplier->id)
            ->where('active_flag', 'A')
            ->exists();

        if ($hasActiveProducts || $hasActiveDetails) {
            return redirect()->route('supplier-index')
                ->with('error', 'Cannot delete supplier: There are active products associated with this supplier.');
        }

        $supplier->delete();

        return redirect()->route('supplier-index')
            ->with('success', 'Supplier deleted successfully!');
    }

}