<?php

namespace App\Http\Controllers\Product;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\ProductPackaging;
use App\Models\ProductPackagingUpload;
use App\Imports\ProductExcelImport;
use App\Models\BusinessDivision;
use App\Models\ProductUpload;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\MenuModelPermission;
use App\Models\ProductFeature;
use App\Models\ProductTestPackage;
use App\Models\Stock;
use Carbon\Carbon;
use Yajra\DataTables\Facades\DataTables;




class ProductPackagingController extends Controller
{
    
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
         $data = ProductPackaging::orderBy('priority','ASC')
        ->paginate(10);

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = ProductPackaging::when(!empty($search_query), function ($query) use ($search_query) {
                        return $query->where('name', 'like', '%'.$search_query.'%');
                    })
                    ->orderBy('priority','ASC')
                    ->paginate($sort_by);

            return view('product-packaging.table', compact('data'));
        }
        else
        {

            return view('product-packaging.index',compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority = ProductPackaging::max('priority');
        $priority = $priority != '' ? $priority : 0;

        return view('product-packaging.create', compact('priority'));
       
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:product_item_types',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method'
        ]);

        ProductPackaging::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Product Item Type has been created successfully',
            ]);
        }

        return redirect()->back()
            ->with('success','Product Item Type has been created successfully');
        }
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data = ProductPackaging::find($id);

        return view('product-packaging.edit',compact('data'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:product_item_types,name,'.$id,
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $package = ProductPackaging::find($id);

        if (!$package) {
            return redirect()->route('product-packaging.index')
                ->with('error','Product packaging not found!');
        }

        $package->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Product packaging has been created successfully',
            ]);
        }

        return redirect()->route('product-packaging.index')
            ->with('success','Product packaging Updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $data = ProductPackaging::find($request->id);

        $data->delete();

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
            ]
        ]);
    }


    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('status' => $request->status );
            $Update = ProductPackaging::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Product Packaging status successfully change'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }



     public function importProductForm(Request $request)
    {
        $query = ProductPackagingUpload::query(); // Use query() method to start a new query

        if ($request->ajax()) {
            $sort_by = $request->get('sortby') ?? 10;
            $sort_type = $request->get('sorttype');
            $search_query = $request->get('query');

            $query->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('name', 'like', '%' . $search_query . '%');
            });

            $data = $query->paginate($sort_by);

            return view('product-packaging.product-packaging-upload.product-import-table', compact('data'));
        } else {
            $data = $query->paginate(10);
            return view('product-packaging.product-packaging-upload.bulk-import', compact('data'));
        }

    }



    public function importForm(Request $request)
    {
        return view('product-packaging.product-packaging-upload.import');
    }

    public function editProduct(Request $request, $id)
    {
        $data = ProductPackagingUpload::find($id);

        return view('product-packaging.product-packaging-upload.edit-modal', compact('data'));
    }

    public function updateProduct(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required',
            'priority' => 'required'
            
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except(['_token']);

        ProductPackagingUpload::whereId($id)->update($data);

        return redirect()->back()
            ->with('success','Product Packaging updated successfully');
    }
     
     public function importBulkProducts(Request $request)
    {
        ini_set('max_execution_time', 500);

        $validator = \Validator::make($request->all(), [
            'file' => 'required|mimes:xlsx'
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => 'The file must be latest version of excel after 2003. File of type: xlsx .',
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $records  = [];
        $data     = Excel::toArray(new ProductExcelImport, $request->file('file'));
        $data     = isset($data[0]) ? $data[0] : [];
        $headings = [];

        if (isset($data[0])) {
            $headings = $data[0];
            unset($data[0]);
        }

        if (!empty($data)) {
            // Truncate table.
            \DB::table('product_packaging_uploads')->truncate();

            foreach ($data as $key => $record) {
                $mfg_date = null;
                $exp_date = null;

                if (empty($record[array_search("Name", $headings)])) {
                    continue;
                }

                $records[$key] = [
                    'name'   => $record[array_search("name", $headings)],
                    'priority'  => $record[array_search("priority", $headings)],
                    'status'              => '1',
                    'created_at'          => now(),
                    'updated_at'          => now(),
                ];
            }

            ProductPackagingUpload::insert($records);

            return response()->json([
                'success' => true,
                'message' => 'Products are uploaded successfully.',
                'data'    => []
            ]);
        } else {
            return response()->json([
                'success' => false,
                'message' => 'Products data not found!',
                'data'    => []
            ]);
        }
    }

      
   

        public function clearData()
            {
                ProductPackagingUpload::truncate();

                return response()->json([
                    'success' => true,
                    'message' => 'Temp data cleared successfully.'
                ]);
            }

        public function importDestroy(Request $request)
    {
        ProductPackagingUpload::find($request->id)->delete();

        $Redirect = 'product-packaging-import.create';

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
                'redirect' => $Redirect,
            ]
        ]);
    }


    public function importProducts(Request $request)
    {
        ini_set('max_execution_time', 500);
        $data      = ProductPackagingUpload::all();
        $duplicate = $unique = $emptyName = $emptyPrimaryUnit = $recordsDeleted = 0;

        $batchSeries = []; // Track the batch series for each product ID
        $processedEmptyBatches = []; // Track product IDs that have been assigned a batch

        if (count($data) > 0) {
            foreach ($data as $key => $record) {
                if (empty($record->name)) {
                    $emptyName += 1;

                    continue;
                }
                $id = $record->id ?? 0;


                $existingProduct = ProductPackaging::where('name', $record->name)
                    ->first();

                if (!$existingProduct) {
                    $created_product = ProductPackaging::create([
                        'name'                 => $record->name,
                        'priority'           => $record->priority,
                        'status'               => '1',
                    ]);

                    \DB::table('product_packaging_uploads')->where('name', $record->name)->delete();
                    $unique += 1;
                } 
                else{
                    $duplicate += 1;
                    $recordsDeleted += 1;
                }
            }
        }

        return response()->json([
            'success' => true,
            'message' => $unique . ' products imported. ' . $duplicate . ' duplicate records skipped.',
            'data' => [
                'inserted' => $unique,
                'deleted' => $recordsDeleted,
                'not_inserted' => $emptyName ,
            ],
        ]);
    }
}
