<?php

namespace Packages\Product\Http\Controllers;

use App\Http\Controllers\Controller;
use Facade\Ignition\Support\Packagist\Package;
use Illuminate\Database\Eloquent\Builder;
use Packages\Product\Http\Requests\ProductRequest;
use Packages\Product\Models\Product;
use Illuminate\Http\Request;
use App\Models\Category;
use App\Models\Upload;
use phpDocumentor\Reflection\Types\Compound;


class ProductController extends Controller
{
    public function __construct()
    {

    }

//  *******************************************show  page product ************
    public function index()
    {
        $categories = Category::orderBy('id', 'DESC')->get();

        $products = Product::query()->orderBy('id', 'DESC');

        if (request()->has('productCategory') && request('productCategory') != '')
            $products = $products->whereHas('categories', function (Builder $query) {
                $query->whereRaw('id = ?', [request('productCategory')]);
            });

        if (request()->has('productStatus') && request('productStatus') != '')
            $products = $products->whereRaw('status = ?', [request('productStatus')]);

        if (request()->has('productName') && request('productName') != '')
            $products = $products->whereRaw('title = ?', [request('productName')]);
        if (request()->has('creatorId') && request('creatorId') != '')
            $products = $products->whereHas('user', function (Builder $query) {
                $query->whereRaw('name= ?', [request('creatorId')]);
            });
        $products = $products->paginate();


        return view('product::index', compact('products', 'categories'));

    }

//**************************************************** page create products *****************
    public function create()
    {
        $categories = Category::orderBy('id', 'DESC')->get();

        return view('product::product.create', compact('categories'));
    }

// *********************************************************save products ******************

    public function store(ProductRequest $request)
    {

        $request->merge([
            'price' => preg_replace('/[^0-9]+/', '', $request->price),
            'sale_price' => preg_replace('/[^0-9]+/', '', $request->sale_price),
        ]);
        $data = [
            'title' => $request->title,
            'slug' => $request->slug,
            'sku' => $request->sku,
            'price' => $request->price,
            'sale_price' => $request->sale_price,
            'type' => $request->type,
            'status' => $request->status,
            'discription' => $request->discription,
            'creator_id' => auth()->user()->id
        ];
        $product = Product::create($data);
        $product->categories()->sync($request->categories);


        if ($request->has('photo')) {
            $file = $request->file('photo');
            $diskName = 'product';
            $this->uploader($file, $diskName, $product);

        }

        $msg = 'ذخیره محصول با موفقیت انجام شد ';
        return redirect(route('products.edit', $product->id))->with('success', $msg);
    }

    // ******************************************************edit page product*********************************************

    public function edit( Product $product)
    {

        $categories = Category::orderBy('id', 'DESC')->get();
        $upload = upload::orderBy('id', 'DESC')->get();
        return view('product::product.edit', compact('product', 'categories', 'upload'));
    }

// *******************************************update page product*****************************************

    public function update(ProductRequest $request, Product $product)
    {

        $request->merge([
            'price' => preg_replace('/[^0-9]+/', '', $request->price),
            'sale_price' => preg_replace('/[^0-9]+/', '', $request->sale_price),
        ]);


        $data = [
            'title' => $request->title,
            'slug' => $request->slug,
            'sku' => $request->sku,
            'price' => $request->price,
            'sale_price' => $request->sale_price,
            'type' => $request->type,
            'status' => $request->status,
            'discription' => $request->discription,
            'creator_id' => auth()->user()->id
        ];

        $product->update($data);

        $product->categories()->sync($request->categories);


        $msg = 'ویرایش محصول با موفقیت انجام شد ';
        dd($request->all());
        return redirect(route('products.index'),compact('upload'))->with('success', $msg);
    }

    //***************************** delete products*****************************************

    public function destroy(Product $product)
    {

        $product->delete();
        {
            return back();
        }
    }

    public function uploader($file, $diskName, $product)
    {
        $fileExtension = $file->getClientOriginalExtension();
        $fileMimeType = $file->getMimeType();

        $afterDiskRoot = '/' . jdate()->format('Y') . '/' . jdate()->format('m');

        $fileName = jdate(time())->format('Ymd') . '_' . $file->getClientOriginalName();

        $filePath = storage_path('app/public/' . $diskName . $afterDiskRoot . '/' . $fileName);

        if (File_exists($filePath)) {
            $fileName = time() . '_' . $fileName;
        }

        $upload = $file->storeAs($afterDiskRoot, $fileName, $diskName);


        $uploadData = [
            'name' => $fileName,
            'path' => $upload,
            'mime_type' => $fileMimeType,
            'extension' => $fileExtension,

        ];

        $uploaded = $product->uploads()->create($uploadData);
        dd($uploaded);

    }
//    public function serveFile(Request $request, $id)
//    {
//        $attachment = Upload::where('uploadable_type', 'Packages\Product\Models\Product')
//            ->where('id', $id)
//            ->firstOrFail();
//
//        if (!\Storage::disk('product')->exists($attachment->path))
//            abort(404);
//        $file_path = \Storage::disk('product')->getDriver()->getAdapter()->getPathPrefix() . $attachment->path;
//
//        return response()->file($file_path);
//    }


}
