<?php


namespace App\Http\Controllers\Administrator\product;


use App\Exports\FabricExport;
use App\Imports\FabricImport;
use App\Model\product\ProductUnitModel;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use App\Model\product\ProductModel;

use Illuminate\Validation\Rule;
use Yajra\DataTables\DataTables;

use Illuminate\Validation\ValidationException;
use Image;

use DB;
use App\Model\product\ProductImageModel;
use App\Fun\Fun;
use Illuminate\Support\Facades\Gate;
use Maatwebsite\Excel\Facades\Excel;

class FabricController extends Controller

{

    function __construct()

    {
        $this->middleware('permission:Material List', ['only' => ['index']]);
        $this->middleware('permission:Material Show', ['only' => ['show']]);
        $this->middleware('permission:Material Create', ['only' => ['create', 'store']]);
        $this->middleware('permission:Material Edit', ['only' => ['update', 'edit']]);
        Fun::lang();
    }

    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = ProductModel::where(['status' => 1, 'type' => 'fabric'])->latest();
            return Datatables::of($data)
                ->addColumn('created_at', function ($product) {
                    return myDate($product->created_at);
                })
                ->addColumn('cost_usd', function ($product) {
                    $cost_usd = $product->cost_usd ?? 0;
                    $cost_riel = $product->cost_riel ?? 0;
                    return '$'.number_format($cost_usd, 2).'<br>៛'.number_format($cost_riel, 2);
                })

                ->addColumn('images', function ($product) {
                    $ProductImage = ProductImageModel::where('product_id',$product->id ??'')->first();
                    return findImg($ProductImage->images ??'');
                })
                ->addColumn('images', function ($product) {
                    $ProductImage = ProductImageModel::where('product_id',$product->id ??'')->first();
                    return findImg($ProductImage->images ??'');
                })
                ->editColumn('color_code', function ($product) {
                    if($product->color_code) {
                        $color = findColor($product->color_code);
                        $name = $color->name ?? '';
                        $color = $color->color ?? 'transparent';
                        return "<i class='fa fa-stop border' style='border:1px solid rgba(1,1,1,0.4);color: $color'></i> $name";
                    }
                })
                ->addColumn('category_id', function ($product) {
                    return $product->get_category->category_name?? '';
                })
                ->editColumn('unit_id', function ($data) {
                    $unit = findUnit($data->unit_id);
                    return $unit ? $unit->unit : '';
                })

                ->addColumn('action', function ($product) {
                    $check_language = Fun::lang();
                    if ($check_language == 'km') {
                        $edit = "កែសម្រួល";
                        $show = 'បង្ហាញ';
                    } else {
                        $edit = "Edit";
                        $show = 'Show';
                    }
                    $btn = '';
                    if (Gate::check('Fabric show') || 1) {
                        $btn .= ' <button type="button" class="button_info btn_purchase_invoice_public" data-href = "' . route("fabric.show", $product->id) . '"  >' . $show . '</button>';
                    }
                    if (Gate::check('Fabric edit')) {
                        $btn .= '<button title="' . $edit . '" class="button_warning edit" data-url = "' . route("fabric.edit", $product->id) . '">' . $edit . '</button>';
                    }
                    if (!1) {
                        $btn .= '<button title="' . __('administrator.delete') . '" class="button_danger delete" data-url = "' . route("fabric-destroy", $product->id) . '"><span class="fa fa-trash"></span></button>';
                    }
                    return $btn;

                })
                ->addIndexColumn()
                ->rawColumns(['images','action','cost_usd','color_code'])
                ->make(true);
        }
        return view('administrator.setup-item.product-fabric.index');
    }

    public function create()

    {
        $unit = getUnit('fabric')->pluck('unit', 'id');
        $category = getCategory('fabric')->pluck('category_name', 'id');
        $code = ProductModel::where('type', 'fabric')->orderBy('id','desc')->first()->id??0;
        $code = 'FB'.sprintf('%05d', $code+1);
        return view('administrator.setup-item.product-fabric.create', compact('category', 'unit','code'));
    }

    public function store(Request $request)
    {
       return $this->update($request,null);
    }

    function show($id)
    {
        $product = ProductModel::find($id);
        return view('administrator.setup-item.product-fabric.show', compact('product'));
    }

    public function edit($id)

    {
        $product = ProductModel::find($id);
        $product_unit = ProductUnitModel::where('product_id', $product->id)->orderBy('qty_per_unit', 'ASC')->get();
        $unit = getUnit('fabric')->pluck('unit', 'id');
        $category = getCategory('fabric')->pluck('category_name', 'id');
        return view('administrator.setup-item.product-fabric.edit', compact('category', 'product', 'unit', 'product_unit'));
    }

    public function update(Request $request,$id)
    {
        $this->validate($request, [
            'product_name' =>'required',
            'barcode' => 'required',
            'category_id' => 'required',
            'color_code' => 'required',
            'child_unit' => 'required',
            'unit_id' => 'required',
            'cost_usd' => 'required',
            'cost_riel' => 'required',
        ]);
        $check_product = ProductModel::where(['product_name'=>$request->product_name,'type'=>'fabric'])->when($id,function ($q) use($id){$q->where('id','!=',$id);})->first();
        $check_barcode = ProductModel::where(['barcode'=>$request->barcode,'type'=>'fabric'])->when($id,function ($q) use($id){$q->where('id','!=',$id);})->first();
        if($check_barcode){
            throw ValidationException::withMessages(['barcode'=>'កូដ មានរួចហើយ']);
        }
        if($check_product){
            throw ValidationException::withMessages(['product_name'=>'ឈ្មោះផលិតផល មានរួចហើយ']);
        }

        $data = $request->all();
        $data['type'] = 'fabric';
        $data['status'] = 1;
        $fabric = ProductModel::updateOrCreate(
            [
                'id'=>$id
            ],$data
        );

        if ($files = $request->file('gallery')) {
            $ProductImage = ProductImageModel::where('product_id', $id)->get();
            foreach ($ProductImage as $file) {
                if (file_exists(public_path() . '/' . $file->$file)) {
                    unlink(public_path() . '/' . $file->images);
                }
                $file->delete();
            }
            $original_name = 'IMG' . date('ymdhis') . '.png';
            $destinationPath = 'images/upload';
            $files->move($destinationPath, $original_name);
            ProductImageModel::Insert([
                'images' => $destinationPath . '/' . $original_name,
                'product_id' => $fabric->id,
            ]);

        }
        return response()->json(['status' => 'success', 'route' => route('fabric.index')]);

    }

    public function destroy($id)

    {

        DB::table('nso007_products')->where('id', $id)->update(['status' => 0]);

        return response()->json([

            'success' => 'Record deleted successfully!'

        ]);

    }

    public function product_changeStatus(Request $request)

    {

        $products = ProductModel::find($request->id);

        $products->status = $request->status;

        $products->save();


        return response()->json(['success' => 'Status change successfully.']);

    }
    public function import_exel(Request $request)
    {
        if ($request->export_sample) {
            return Excel::download(new FabricExport(), 'fabric.xlsx');
        }
        if ($request->method() === 'POST') {
            $this->validate($request, [
                'file' => 'required|file|max:10000|mimes:xlsx,csv',
            ]);
            if (request()->hasFile('file')) {
                $path = $request->file('file');
                Excel::import(new FabricImport(), $path);
                return response()->json(['status' => 'success', 'reload' => 1]);
            }
        }
        return view('component.import-exel', ['route' => 'fabric-import-exel']);
    }

    public function delete($id)
    {
        ProductUnitModel::where('product_id', $id)->delete();
        ProductImageModel::where('product_id', $id)->delete();
        ProductModel::find($id)->delete();
        return response()->json('ok');
    }

}

