<?php

namespace App\Http\Controllers\Backend\InventorySetup;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Transformers\SupplierTransformer;
use App\Models\Branch;
use App\Models\ChartOfAccount;
use App\Models\Navigation;
use App\Models\Stockin;
use App\Models\Supplier;
use App\Services\InventorySetup\SupplierService;
use App\Services\Settings\BranchService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Validator;





class SupplierController extends Controller
{

    /**
     * @var supplierService
     */
    private $systemService;
    /**
     * @var supplierTransformer
     */
    private $systemTransformer;

    /**
     * CategoryController constructor.
     * @param supplierService $systemService
     * @param supplierTransformer $systemTransformer
     */
    public function __construct(SupplierService $supplierService, SupplierTransformer $supplierTransformer)
    {
        $this->systemService = $supplierService;

        $this->systemTransformer = $supplierTransformer;
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        $title = 'Supplier List';
        return view('backend.pages.inventories.supplier.index', get_defined_vars());
    }

 public function due(Request $request)
{
    $title = 'Supplier List';
    $auth = Auth::user();
    $suppliers = Supplier::orderBy('id', 'desc')->get();

    $from = $request->from_date;
    $to = $request->to_date;

    $query = Supplier::query();

    if ($auth->type !== "Admin") {
        $query->where('branch_id', $auth->branch_id);
    }

    // Filter supplier only when NOT "all"
    if ($request->supplier_id && $request->supplier_id !== 'all') {
        $query->where('id', $request->supplier_id);
    }

    if ($from && $to) {
        $query->whereBetween('created_at', [$from, $to]);
    }

    // Fetch suppliers
    $supplierDueList = $query->get()->map(function($supplier) {
        $chartOfAccount = \App\Models\ChartOfAccount::where([
            'accountable_id'   => $supplier->id,
            'accountable_type' => \App\Models\Supplier::class,
        ])->first();

        // Add a new property for sorting
        $supplier->due_amount = $chartOfAccount ? supplierDue($chartOfAccount->id) : 0;
        return $supplier;
    });

    // Sort descending by due amount
    $supplierDueList = $supplierDueList->sortByDesc('due_amount');

    $supplierDue = $supplierDueList->sum('due_amount');

    return view('backend.pages.inventories.supplier.due', get_defined_vars());
}



    // public function due(Request $request)
    // {
    //     $title = 'Supplier List';

    //     $auth = Auth::user();

    //     if ($auth->type !== "Admin") {
    //         $supplierDue = Supplier::where('branch_id', $auth->branch_id)
    //             ->sum('totalDue');

    //         $supplierDueList = Supplier::where('branch_id', $auth->branch_id)
    //             ->whereNotNull('totalDue')
    //             ->orderByDesc('totalDue')
    //             ->get();
    //     } else {
    //         $supplierDue = Supplier::sum('totalDue');

    //         $supplierDueList = Supplier::whereNotNull('totalDue')
    //             ->orderByDesc('totalDue')
    //             ->get();
    //     }


    //     return view('backend.pages.inventories.supplier.due', get_defined_vars());
    // }


    public function dataProcessingSupplier(Request $request)
    {
        $json_data = $this->systemService->getList($request);
        return json_encode($this->systemTransformer->dataTable($json_data));
    }

    public function dataProcessingSupplierDashboard(Request $request)
    {
        $json_data = $this->systemService->getDashboardList($request);
        return json_encode($this->systemTransformer->dataTable($json_data));
    }

    public function dataProcessingSupplierDue(Request $request)
    {
        $json_data = $this->systemService->getDueList($request);
        return json_encode($this->systemTransformer->dataTable($json_data));
    }

    public function show($id = null)
    {
        $title = 'Supplier Details';
        $supplier = Supplier::where('id', $id)->first();
        $ledgerId = ChartOfAccount::where('accountable_id', $supplier->id)
            ->where('accountable_type', 'App\Models\Supplier')
            ->first();
        $supplierId = $ledgerId->id;
        //  dd($supplier);
        $totalDue = supplierDue($supplierId);
 
        $query = Stockin::where('ledger_id', $supplierId);

        // Check for date filters
        if (request('from_date')) {
            $query->whereDate('date', '>=', request('from_date'));
        }

        if (request('to_date')) {
            $query->whereDate('date', '<=', request('to_date'));
        }

        $stockIn = $query->orderBy('id','desc')->get();

        return view('backend.pages.inventories.supplier.details', get_defined_vars());
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create()
    {
        $title = 'Add New Supplier';
        $suppliertLastData = Supplier::latest('id')->first();
        if ($suppliertLastData) :
            $suppliertData = $suppliertLastData->id + 1;
        else :
            $suppliertData = 1;
        endif;
        $supplierCode = 'SP' . str_pad($suppliertData, 5, "0", STR_PAD_LEFT);

        $auth = Auth::user();

        $userRole = $auth->role_id;
        if ($userRole > 1) {

            $branchs = Branch::where("parent_id", 0)->where("id", $auth->branch_id)->get();
            $branch = Branch::get()->where('status', 'Active');
        } else {

            $branchs = Branch::where("parent_id", 0)->get();
            $branch = Branch::get()->where('status', 'Active');
        }


        $suppliers = Supplier::get();
        return view('backend.pages.inventories.supplier.create', get_defined_vars());
    }
    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {

        try {
            $this->validate($request, $this->systemService->storeValidation($request));
        } catch (ValidationException $e) {
            session()->flash('error', 'Validation error !!');
            return redirect()->back()->withErrors($e->errors())->withInput();
        }
        $this->systemService->store($request);
        session()->flash('success', 'Data successfully save!!');
        return redirect()->route('inventorySetup.supplier.index');
    }
    /**
     * @param $slug
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit($id)
    {
        if (!is_numeric($id)) {
            session()->flash('error', 'Edit id must be numeric!!');
            return redirect()->back();
        }
        $editInfo =   $this->systemService->details($id);
        if (!$editInfo) {
            session()->flash('error', 'Edit info is invalid!!');
            return redirect()->back();
        }
        $branchs = Branch::where("parent_id", 0)->get();
        $branch = Branch::get()->where('status', 'Active');

        $title = 'Add New Supplier';
        return view('backend.pages.inventories.supplier.edit', get_defined_vars());
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id)
    {
        //dd($request->all());
        if (!is_numeric($id)) {
            session()->flash('error', 'Edit id must be numeric!!');
            return redirect()->back();
        }
        $editInfo = $this->systemService->details($id);
        if (!$editInfo) {
            session()->flash('error', 'Edit info is invalid!!');
            return redirect()->back();
        }
        try {
            $this->validate($request, $this->systemService->updateValidation($request, $id));
        } catch (ValidationException $e) {
            session()->flash('error', 'Validation error !!');
            return redirect()->back()->withErrors($e->errors())->withInput();
        }
        $this->systemService->update($request, $id);
        session()->flash('success', 'Data successfully updated!!');
        return redirect()->route('inventorySetup.supplier.index');
    }

    /**
     * @param $slug
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function statusUpdate($id, $status)
    {
        if (!is_numeric($id)) {
            return response()->json($this->systemTransformer->invalidId($id), 200);
        }
        $detailsInfo =   $this->systemService->details($id);
        if (!$detailsInfo) {
            return response()->json($this->systemTransformer->notFound($detailsInfo), 200);
        }
        $statusInfo =  $this->systemService->statusUpdate($id, $status);
        if ($statusInfo) {
            return response()->json($this->systemTransformer->statusUpdate($statusInfo), 200);
        }
    }


    /**
     * @param $slug
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function destroy($id)
    {
        if (!is_numeric($id)) {
            return response()->json($this->systemTransformer->invalidId($id), 200);
        }
        $detailsInfo =   $this->systemService->details($id);
        if (!$detailsInfo) {
            return response()->json($this->systemTransformer->notFound($detailsInfo), 200);
        }
        $deleteInfo =  $this->systemService->destroy($id);
        if ($deleteInfo) {
            return response()->json($this->systemTransformer->delete($deleteInfo), 200);
        }
    }


    public function restoreList()
    {
        $title = 'Restore User List';
        $users =  Supplier::onlyTrashed()->get();
        return view('backend.pages.inventories.supplier.restore', get_defined_vars());
    }

    public function restore($id)
    {
        try {
            $user = Supplier::withTrashed()->findOrFail($id);
            $user->restore();

            return response()->json([
                'success' => true,
                'message' => 'User restored successfully!'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error restoring user: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Permanently delete the specified resource.
     */
    public function forceDelete($id)
    {
        try {
            $user = Supplier::withTrashed()->findOrFail($id);
            $chartOfAccount = ChartOfAccount::where('accountable_id', $user->id)->where('accountable_type', 'App\Models\Supplier')->count();
            if ($chartOfAccount > 0) {
                return response()->json([
                    'success' => false,
                    'message' => 'You cannot delete this Supplier because related chart of account entries exist.'
                ], 403);
            }
            $user->forceDelete(); // This will permanently delete the user

            return response()->json([
                'success' => true,
                'message' => 'User permanently deleted!'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error permanently deleting user: ' . $e->getMessage()
            ], 500);
        }
    }
}
