<?php

namespace App\Http\Controllers\Backend\InventorySetup;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Transformers\CustomerTransformer;
use App\Models\Branch;
use App\Models\ChartOfAccount;
use App\Models\Navigation;
use App\Models\Customer;
use App\Models\CustomerGroup;
use App\Services\InventorySetup\CustomerService;
use App\Services\Settings\BranchService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Validator;





class CustomerController extends Controller
{

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

    /**
     * CategoryController constructor.
     * @param supplierService $systemService
     * @param supplierTransformer $systemTransformer
     */

    public function __construct(CustomerService $customerService, CustomerTransformer $customerTransformer)
    {
        $this->systemService = $customerService;

        $this->systemTransformer = $customerTransformer;
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {

        $title = 'Customer List';
        return view('backend.pages.inventories.customer.index', get_defined_vars());
    }


    public function dashboard(Request $request){
        $title = 'Customer List';
        $customerCount = Customer::count();
        return view('backend.pages.inventories.customer.customer', get_defined_vars());
    }
  public function due(Request $request){
        $title = 'Customer Due List';
        $customerDue = customerDue();
      
        return view('backend.pages.inventories.customer.due', get_defined_vars());
    }

    public function dataProcessingCustomer(Request $request)
    {
        $json_data = $this->systemService->getList($request);
        return json_encode($this->systemTransformer->dataTable($json_data));
    }
     public function dataProcessingCustomerDashboard(Request $request)
    {
        $json_data = $this->systemService->getDashboardList($request);
        return json_encode($this->systemTransformer->dataTable($json_data));
    }
       public function dataProcessingCustomerDue(Request $request)
    {
        $json_data = $this->systemService->getDueList($request);
        return json_encode($this->systemTransformer->dataTable($json_data));
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create()
    {
        $title = 'Add New Customer';
        $customertLastData = Customer::latest('id')->first();
        if ($customertLastData) :
            $customerData = $customertLastData->id + 1;
        else :
            $customerData = 1;
        endif;
        $customerCode = 'CU' . str_pad($customerData, 5, "0", STR_PAD_LEFT);
         $auth = Auth::user();
     
         $userRole = $auth->role_id;
         if($userRole > 1) {
          
                $branchs = Branch::where("id", $auth->branch_id)->get();
        $branch = Branch::get()->where("id", $auth->branch_id)->where('status', 'Active');
         }else{
         $branchs = Branch::where("parent_id", 0)->get();
        $branch = Branch::get()->where('status', 'Active');
         }
      
        $customerGroup = CustomerGroup::all();
        return view('backend.pages.inventories.customer.create', get_defined_vars());
    }
      public function show($id =null){
          $title = 'Customer Details';
             $customer = Customer::where('id',$id)->first();
                $ledgerId = ChartOfAccount::where('accountable_id', $customer->id)
         ->where('accountable_type', 'App\Models\Customer')
          ->first();
         $customerId = $ledgerId->id;
             $totalDue = customerDueTotal($customerId);
            //  dd($customer);
         return view('backend.pages.inventories.customer.details', 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.customer.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();
        }
        $branch = Branch::get()->where('status', 'Active');
        $branchs = Branch::where("parent_id", 0)->get();
        $customerGroup = CustomerGroup::all();
        $title = 'Add New Customer';
        return view('backend.pages.inventories.customer.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.customer.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 =  Customer::onlyTrashed()->get(); 
          return view('backend.pages.inventories.customer.restore',get_defined_vars());
    }

        public function restore($id)
    {
        try {
            $user = Customer::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 = Customer::withTrashed()->findOrFail($id);
            $chartOfAccount = ChartOfAccount::where('accountable_id',$user->id)->where('accountable_type','App\Models\Customer')->count();
              if ($chartOfAccount > 0) {
            return response()->json([
                'success' => false,
                'message' => 'You cannot delete this customer 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);
        }
    }
}
