<?php

namespace App\Http\Controllers\Api;

use App\Http\Resources\ItemCollection;
use App\Http\Resources\ItemRatesCollection;
use App\Http\Resources\ItemResource;
use App\Models\Attach;
use App\Models\Item;
use App\Models\ItemDetails;
use App\Models\Rate;
use Illuminate\Http\Request;
use Validator;
use App\Http\Controllers\Controller;

class ItemController extends Controller
{
    public function index () {
        $data = Item::get();

        return response()->json(['data' => new ItemCollection($data)]);
    }
    public function show ($id) {
        Validator::make(['id' => $id],
            [
                'id' => ['required','integer', 'exists:items,id'],
            ])->validate();
        $data = Item::findOrFail($id);
//return $data;
        return response()->json(['data' => new ItemResource($data),]);

    }

    public function itemRates ($id) {
        Validator::make(['id' => $id],
            [
                'id' => ['required','integer', 'exists:items,id'],
            ])->validate();
        $data = Item::findOrFail($id);
        $isRated = $this->isRated($id);
        return response()->json(['data' => [
            'data' => new ItemRatesCollection($data->rates),
            'is_rated' => $isRated,
            'item_rate' => $data->rate,
        ]]);
    }

    public function isRated ($id) {
        $check = Rate::where('user_id' ,auth('api')->id())->where('item_id' ,$id)->first();
        return (!$check) ? false: true;
    }

    public function store(Request $request)
    {
        $request->validate([
            'title'  => 'required|string|max:255',
            'description'  => 'required|string|max:255',
            'brand'  => 'required|integer|exists:brands,id',
            'classification'  => 'required|integer|exists:classifications,id',
            'price'     => 'required|integer|min:1',
            'images'     => 'required|array',
            'images.*' => 'required|image|mimes:png,jpg,jpeg|max:5120',
        ]);


        $inputs['title'] = $request->title;
        $inputs['description'] = $request->description;
        $inputs['brand_id']  = $request->brand;
        $inputs['classification_id'] = $request->classification;
//        $inputs['stock']    = $request->stock;
        $inputs['price']    = $request->price;
        $inputs['type']     = $request->type;

        $create = Item::create($inputs);
        if (!$create) {
            return back()->with('error',trans('response.failed'));
        }
        if (request()->hasFile('images')) {
            $images = request()->file('images');
            foreach ($images as $index => $image) {
                $imageName = md5(time().$index). '.'.$image->getClientOriginalExtension();
                $imageMove = $image->move(public_path('uploads/attaches'),$imageName);
                if (!$imageMove) {
                    return back()->with('error',trans('response.failed'));
                }
                Attach::create([
                    'item_id' => $create->id,
                    'image' => $imageName,
                ]);
            }
        }
        // store item details
        if (request()->has('details') && request()->details != null) {
            foreach (request()->details as $detail) {
                if(!empty($detail["key"]) && !empty($detail["value"])):
                    ItemDetails::create([
                        'item_id' => $create->id,
                        'key' => $detail["key"],
                        'value' => $detail["value"]
                    ]);
                endif;
            }
        }
//        return back()->with('success',trans('response.added'));
        return response()->json(['data' => new ItemResource($create),]);
    }
}
