<?php

namespace App\Http\Controllers\Product;

use App\Http\Controllers\Controller;
use App\Models\PrimaryUnit;
use App\Models\TestItem;
use App\Models\TestItemNormalRange;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\ImportPrimaryUnit;
use App\Exports\ExportPrimaryUnitFormat;
use Session;

class PrimaryUnitController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:primary-unit-list', ['only' => ['index']]);
    }

    public function index(Request $request)
    {
        $data = PrimaryUnit::select([
                    'primary_units.id',
                    'primary_units.unit_type',
                    'primary_units.code',
                    'primary_units.name',
                    'primary_units.description',
                    'primary_units.status',
                    'primary_units.is_default',
                    'primary_units.priority'
                ])->latest();

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

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                            return $query->where('primary_units.name', 'like', '%'.$search_query.'%')
                                ->orWhere('primary_units.description', 'like', '%'.$search_query.'%')
                                ->orWhere('primary_units.code', 'like', '%'.$search_query.'%');
                        })
                        ->paginate($sort_by);

            return view('primary-unit.table', compact('data'));
        }
        else
        {
            $data = $data->paginate(10);

            return view('primary-unit.index', compact('data'));
        }
    }

    public function create()
    {
        $priority = PrimaryUnit::max('priority');
        $priority = $priority != '' ? $priority : 0;
        return view('primary-unit.create',compact('priority'));
    }

    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:primary_units,name,NULL,id,deleted_at,NULL',
        ]);

        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'
        ]);

        $primary = PrimaryUnit::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Primary unit created successfully.',
                'data'    => $primary
            ]);
        }

        return redirect()->route('primary-units.index')
            ->with('success','Primary unit created successfully');
    }

    public function edit($id)
    {
        $data = PrimaryUnit::find($id);

        return view('primary-unit.edit',compact('data'));
    }

    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:primary_units,name,'.$id.',id,deleted_at,NULL',
        ]);

        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'
        ]);

        $primary = PrimaryUnit::find($id);

        if (!$primary) {
            return redirect()->route('primary-units.index')
                ->with('error','Primary Unit not found!');
        }

        $primary->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Primary unit created successfully.',
                'data'    => $primary
            ]);
        }

        return redirect()->route('primary-units.index')
            ->with('success','Primary unit Updated successfully');
    }

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

            $Redirect = 'primary-units';

            if($Update){
                return response()->json([
                    'success' => true,
                    'message' => ['Primary Unit status successfully change'],
                    'data'    => [
                        'redirect' => $Redirect,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data'    => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }

    public function destroy(Request $request)
    {
        PrimaryUnit::find($request->id)->delete();

        $Redirect = 'primary-units';

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

    public function importCreate()
    {
       return view('primary-unit.import');
    }

    public function importPreview(Request $request)
    {
        $primary_units_data = [];

        Session::put('PrimaryUnitsData', $primary_units_data);

        try {
            Excel::import(new ImportPrimaryUnit, $request->file('primary_units'));

            $data = Session::get('PrimaryUnitsData');

            return view('primary-unit.preview', compact('data'));

        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => [$e->getMessage()],
            ]);
        }
    }

    public function importSessionDestroy(Request $request)
    {
        $primary_units_data = Session::get('PrimaryUnitsData');

        unset($primary_units_data[$request->id]);

        Session::put('PrimaryUnitsData', $primary_units_data);

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

    public function importStore(Request $request)
    {
        $data = Session::get('PrimaryUnitsData');

        if($data){

            foreach ($data as $row){

                $primary_units = ([
                    'name'        => $row[0],
                    'description' => $row[1],
                    'status'      => ($row[2] == 'Inactive') ? '0' : '1',
                ]);

                $exist_primary_units = PrimaryUnit::where('name', $row[0])->exists();

                if(!$exist_primary_units){
                    PrimaryUnit::create($primary_units);
                }
            }

            return redirect()->route('primary-units.index')
                ->with('success','Primary Units uploaded successfully');
        }else{
           return redirect()->back()
                ->with('error','Empty file uploaded');
        }
    }

    public function exportFormat()
    {
        return Excel::download(new ExportPrimaryUnitFormat, 'primary-unit-format.xlsx');
    }

   public function changeDefault(Request $request)
   {
       if ($request->ajax())
       {
            $data  = array('is_default' => $request->status );
            $count = PrimaryUnit::where(['is_default' => $request->status])->count();

            if ($count > 0 && $request->status == 1) {
                return response()->json([
                    'success' => false,
                    'message' => ['There is already a default primary unit!'],
                    'data'    => []
                ]);
            }

           $Update = PrimaryUnit::where('id', '=', $request->id)->update($data);

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