<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\Brand;
use App\Models\BusinessSetting;
use App\Models\Category;
use App\Models\Product;
use App\Models\Purchase;
use App\Models\PurchaseItem;
use App\Models\Supplier;
use App\Models\Unit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ProductController extends Controller
{
    public function index(Request $request)
    {
        $data['products'] = Product::with(['brand', 'category', 'unit.related_unit'])
                                    ->orderBy('created_at', 'DESC')->paginate(10);
        $data['product_id'] = $request->product_id;
        $data['category_id'] = $request->category_id;
        $data['barcode'] = $request->barcode;
        $data['com'] = BusinessSetting::where('id',6)->first();

        if($request->product_id != null){
            $data['products'] = Product::with(['brand', 'category', 'unit.related_unit'])
                ->where('id',$request->product_id)
                ->orderBy('created_at', 'DESC')
                ->paginate(10)->appends([
                    'product_id' => $request->product_id,
                ]);
        }
        if($request->barcode != null){
            $data['products'] = Product::with(['brand', 'category', 'unit.related_unit'])
                ->where('barcode',$request->barcode)
                ->orderBy('created_at', 'DESC')
                ->paginate(10);
        }
        if($request->category_id != null){
            $data['products'] = Product::with(['brand', 'category', 'unit.related_unit'])
                ->where('category_id',$request->category_id)
                ->orderBy('created_at', 'DESC')
                ->paginate(30)
                    ->appends([
                        'category_id' => $request->category_id,
                    ]);
        }
        if($request->category_id != null && $request->product_id != null){
            $data['products'] = Product::with(['brand', 'category', 'unit.related_unit'])
                ->where('category_id',$request->category_id)->where('id',$request->product_id)
                ->orderBy('created_at', 'DESC')
                ->paginate(10)
                ->appends([
                    'category_id' => $request->category_id,
                    'product_id' => $request->product_id,
                ]);
        }

        return view('backend.pages.product.index', $data);
    }

    public function create()
    {
        $brands = Brand::all();
        $categories = Category::all();
        $units = Unit::all();
        $suppliers = Supplier::all();
        return view('backend.pages.product.create', compact('brands', 'categories', 'units', 'suppliers'));
    }

    public function store(Request $request)
    {
        // dd($request->all());
        $request->validate(
            [
                'name' => 'required|unique:products',
                'barcode' => 'unique:products',
                'category_id' => 'required',
                'unit_id' => 'required',
                'purchase_price' => 'required',
                'selling_price' => 'required',
                'status' => 'required',
            ],
            [
                'name.unique' => 'The product name has already been taken !',
                'barcode.unique' => 'The product barcode has already been taken !',
            ]
        );

        $product = new Product();
        $product->name = $request->name;
        $numberBarcode = rand(000000, 999999);
        if ($request->barcode == NULL) {
            $product->barcode = $numberBarcode;
        } else {
            $product->barcode = $request->barcode;
        }
        $product->category_id = $request->category_id;
        $product->brand_id = $request->brand_id;
        $product->unit_id = $request->unit_id;
        $product->main_qty = $request->main_qty;
        $product->sub_qty = $request->sub_qty;
        $product->purchase_price = $request->purchase_price;
        $product->selling_price = $request->selling_price;
        $product->status = $request->status;
        $product->description = $request->description;
        
        $image = $request->file('images');
        if ($image) {
            $imgName = date('YmdHi') . $image->getClientOriginalName();
            $image->move('public/uploads/products/', $imgName);
            $product->images = $imgName;
        } 
        $product->save();
        // if($request->main_qty != null || $request->main_qty != null && $request->sub_qty != null){
        //     $this->open_stock_purchase($request, $product->id);
        // }
        notify()->success('Product created successfully!');
        return Redirect()->route('product.index');
    }

    public function edit(string $id)
    {
        $data['brands'] = Brand::all();
        $data['categories'] = Category::all();
        $data['units'] = Unit::all();
        $data['suppliers'] = Supplier::all();
        $data['data'] = Product::with(['brand', 'category', 'unit.related_unit'])->where('id', $id)->first();
        return view('backend.pages.product.edit', $data);
    }

    public function update(Request $request, string $id)
    {
        $request->validate([
            'name' => 'required',
            'barcode' => 'numeric',
            'category_id' => 'required',
            'purchase_price' => 'required',
            'selling_price' => 'required',
            'status' => 'required',
        ]);

        $product = Product::findorfail($id);
        $product->name = $request->name;
        $numberBarcode = rand(000000, 999999);
        if ($product->barcode == NULL) {
            $product->barcode = $numberBarcode;
        } else {
            $product->barcode = $request->barcode;
        }
        $product->category_id = $request->category_id;
        $product->brand_id = $request->brand_id;
        $product->purchase_price = $request->purchase_price;
        $product->selling_price = $request->selling_price;
        $product->status = $request->status;
        $product->description = $request->description;
        $image = $request->file('images');
        if ($image) {
            $imgName = date('YmdHi') . $image->getClientOriginalName();
            $image->move('public/uploads/products/', $imgName);
            if (file_exists('public/uploads/products/' . $product->images) and !empty($product->images)) {
                unlink('public/uploads/products/' . $product->images);
            }
            $product->images = $imgName;
            $product->save();
            notify()->success('Product update successfully!');
            return Redirect()->route('product.index');
        } else {
            $product->images = $request->old_image;
            $product->save();
            // if($request->main_qty != null || $request->main_qty != null && $request->sub_qty != null){
            //     $this->open_stock_purchase($request, $product->id);
            // }
            notify()->success('Product update successfully!');
            return Redirect()->route('product.index');
        }
    }

    public function destroy(string $id)
    {
        $product = Product::findorfail($id);
        if (file_exists('public/uploads/products/' . $product->images) and !empty($product->images)) {
            unlink('public/uploads/products/' . $product->images);
        }
        $product->delete();
        notify()->success('Successfully Product Delete!');
        return back();
    }

    public function search(Request $request){
        $data['product_id'] = $request->product_id;
        $data['category_id'] = $request->category_id;

        if($request->product_id != null){
            $data['products'] = Product::with(['brand', 'category', 'unit.related_unit'])
                ->where('id',$request->product_id)
                ->paginate(10);
        }
        if($request->category_id != null){
            $data['products'] = Product::with(['brand', 'category', 'unit.related_unit'])
                ->where('category_id',$request->category_id)
                ->paginate(10);
        }
        return view('backend.pages.product.index', $data);
    }
    public function show(){

    }
}
