<?php

namespace App\Http\Controllers;

use App\Models\MasterFormulation;
use App\Http\Requests\MasterFormulationRequest;

use App\Services\MasterFormulationService;
use App\Services\ProductService;
use App\Models\Product;
use App\Services\RawMaterialItemService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class MasterFormulationController extends Controller
{
    protected $masterFormulationService;
    protected $productService, $rawMaterialItem;
    public function __construct(
        MasterFormulationService $masterFormulationService,
        ProductService $productService,
        RawMaterialItemService $rawMaterialItemService
        )
    {
        $this->masterFormulationService = $masterFormulationService;
        $this->productService = $productService;
        $this->rawMaterialItem = $rawMaterialItemService;
    }

    public function index()
    {
        // if (!auth()->user()->hasPermission('Master Formulation List')) {
        //     abort(403, 'Unauthorized action.');
        // }
        $masterFormulations = $this->masterFormulationService->getAllMasterFormulations();
        if (request()->ajax()) {
            return response()->json([
                'master_formulations' => $masterFormulations,
            ]);
        }
        return view('admin.master-formulations.index', compact('masterFormulations'));
    }

    public function create()
    {
        if (!auth()->user()->name == 'admin') {
            abort(403, 'Unauthorized action.');
        }
        $brandNames = $this->productService->getDistinctBrandNames();
        $rawMaterialItems = $this->rawMaterialItem->getAllRawMaterialItems();

        return view('admin.master-formulations.create', compact('brandNames', 'rawMaterialItems'));
    }

    public function store(MasterFormulationRequest $request)
    {
        if (!auth()->user()->name == 'admin') {
            abort(403, 'Unauthorized action.');
        }
        $data = $this->masterFormulationService->createMasterFormulation($request);
        return redirect()->route('master-formulations.show', ['master_formulation' => $data->id])->with('success', 'Master Formulation created successfully.');
    }

    public function show($id)
    {
        if (!auth()->user()->name == 'admin') {
            abort(403, 'Unauthorized action.');
        }
        $masterFormulation = $this->masterFormulationService->getMasterFormulationById($id);
        $previous = MasterFormulation::where('id', '<', $masterFormulation->id)
            ->orderBy('id', 'desc')
            ->first();

        $next = MasterFormulation::where('id', '>', $masterFormulation->id)
            ->orderBy('id', 'asc')
            ->first();

        // Get all purchase orders for the dropdown (ordered by creation date, newest first)
        $allMfs = MasterFormulation::orderBy('created_at', 'desc')
            ->select('id', 'brand_name', 'created_at')
            ->get();
        return view('admin.master-formulations.show', compact('masterFormulation', 'previous', 'next', 'allMfs'));
    }

    public function edit($id)
    {
        if (!auth()->user()->name == 'admin') {
            abort(403, 'Unauthorized action.');
        }
        $rawMaterialItems = $this->rawMaterialItem->getAllRawMaterialItems();
        $masterFormulation = $this->masterFormulationService->getMasterFormulationById($id);
        $brandNames = $this->productService->getDistinctBrandNames();

        return view('admin.master-formulations.edit', compact('masterFormulation', 'brandNames', 'rawMaterialItems'));
    }

    public function update(MasterFormulationRequest $request, MasterFormulation $masterFormulation)
    {
        if (!auth()->user()->name == 'admin') {
            abort(403, 'Unauthorized action.');
        }
        $data = $this->masterFormulationService->updateMasterFormulation($masterFormulation, $request);
        return redirect()->route('master-formulations.show', ['master_formulation' => $data->id])->with('success', 'Master Formulation updated successfully.');
    }

    public function destroy(MasterFormulation $masterFormulation)
    {
        if (!auth()->user()->name == 'admin') {
            abort(403, 'Unauthorized action.');
        }
        $this->masterFormulationService->deleteMasterFormulation($masterFormulation);
        return redirect()->route('master-formulations.index')->with('success', 'Master Formulation deleted successfully.');
    }

    public function getMasterFormulationsByProduct($productId)
    {
        $product = Product::findOrFail($productId);
        $brandName = $product->brand_name;

        $items = MasterFormulation::where('brand_name', $brandName)
            ->orderBy('product_name')
            ->get(['id', 'product_name', 'batch_size']);

        return response()->json([
            'brand_name' => $brandName,
            'products' => $items,
        ]);
    }

    public function getDetails($id)
    {
        $mf = MasterFormulation::findOrFail($id, ['id', 'product_name', 'batch_size']);
        return response()->json([
            'id' => $mf->id,
            'product_name' => $mf->product_name,
            'batch_size' => $mf->batch_size,
        ]);
    }
}
