<?php

namespace App\Http\Controllers;

use App\Models\PurchaseRequisition;
use App\Http\Requests\PurchaseRequisitionRequest;
use App\Services\PurchaseRequisitionService;
use App\Services\CompanyService;
use App\Services\SupplierService;

class PurchaseRequisitionController extends Controller
{
    protected $companyService;
    protected $purchaseRequisitionService;
    protected $supplierService;

    public function __construct(PurchaseRequisitionService $purchaseRequisitionService, CompanyService $companyService, SupplierService $supplierService)
    {
        $this->companyService = $companyService;
        $this->purchaseRequisitionService = $purchaseRequisitionService;
        $this->supplierService = $supplierService;
    }

    public function index()
    {
        if (!auth()->user()->hasPermission('Purchase Requisition List')) {
            abort(403, 'Unauthorized action.');
        }
        $purchaseRequisitions = $this->purchaseRequisitionService->getAllPurchaseRequisitions();
        return view('admin.purchase-requisitions.index', compact('purchaseRequisitions'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        if (!auth()->user()->hasPermission('Purchase Requisition Create')) {
            abort(403, 'Unauthorized action.');
        }
        if (auth()->user()->hasRole('Superadmin')) {
            $newPurchaseRequisitionCode = "MPR";
        } else {
            $newPurchaseRequisitionCode = $this->purchaseRequisitionService->createPurchaseRequisitionCode(auth()->user()->employee->company_id);
        }
        $companies = $this->companyService->getAllCompanies();
        $suppliers = $this->supplierService->getAllSuppliers();
        $defaultCompany = $companies->where('name', 'Benson Pharmaceuticals')->first();
        $defaultCompanyId = $defaultCompany->id;
        return view('admin.purchase-requisitions.create', compact('companies', 'suppliers', 'newPurchaseRequisitionCode', 'defaultCompanyId'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(PurchaseRequisitionRequest $request)
    {
        try {
            // dd($request->all());
            if (!auth()->user()->hasPermission('Purchase Requisition Create')) {
                abort(403, 'Unauthorized action.');
            }

            $model = $this->purchaseRequisitionService->createPurchaseRequisition($request->validated());
            return redirect()->route('purchase-requisitions.show', $model->id)->with('success', 'Purchase Requisition created successfully.');
        } catch (\Throwable $th) {
            return redirect()->back()->with('error', $th->getMessage());
        }
    }

    /**
     * Display the specified resource.
     */
    public function show($id)
    {
        if (!auth()->user()->hasPermission('Purchase Requisition View')) {
            abort(403, 'Unauthorized action.');
        }
        $purchaseRequisition = $this->purchaseRequisitionService->getPurchaseRequisitionById($id);

        $previous = PurchaseRequisition::where('id', '<', $purchaseRequisition->id)
            ->orderBy('id', 'desc')
            ->first();

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

        $allPRs = PurchaseRequisition::orderBy('created_at', 'desc')
            ->select('id', 'code', 'created_at')
            ->get();

        return view('admin.purchase-requisitions.show', compact('purchaseRequisition', 'previous', 'next', 'allPRs'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        if (!auth()->user()->hasPermission('Purchase Requisition Update')) {
            abort(403, 'Unauthorized action.');
        }
        $purchaseRequisition = $this->purchaseRequisitionService->getPurchaseRequisitionById($id);
        $companies = $this->companyService->getAllCompanies();
        $suppliers = $this->supplierService->getAllSuppliers();
        return view('admin.purchase-requisitions.edit', compact('purchaseRequisition', 'companies', 'suppliers'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(PurchaseRequisitionRequest $request, PurchaseRequisition $purchaseRequisition)
    {
        // dd($request->all());
        try {
            if (!auth()->user()->hasPermission('Purchase Requisition Update')) {
                abort(403, 'Unauthorized action.');
            }

            $model = $this->purchaseRequisitionService->updatePurchaseRequisition($purchaseRequisition, $request->validated());
            return redirect()->route('purchase-requisitions.show', $model->id)->with('success', 'Purchase Requisition updated successfully');
        } catch (\Throwable $th) {
            return redirect()->back()->with('error', $th->getMessage());
        }
    }

    public function destroy(PurchaseRequisition $purchaseRequisition)
    {
        if (!auth()->user()->hasPermission('Purchase Requisition Delete')) {
            abort(403, 'Unauthorized action.');
        }
        $this->purchaseRequisitionService->deletePurchaseRequisition($purchaseRequisition);
        return redirect()->route('purchase-requisitions.index')->with('success', 'Purchase Requisition deleted successfully');
    }

    public function createCodeByCompany($companyId)
    {
        $purchase_requisition_code = $this->purchaseRequisitionService->createPurchaseRequisitionCode($companyId);
        return response()->json(['purchase_requisition_code' => $purchase_requisition_code]);
    }
}
