<?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\Variation;
use App\Models\ProductSize;
use App\Models\ProductColor;
use App\Models\ProductVariation;
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)
    {
        if(env('APP_SC') == 'yes'){

            $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)
                    ->paginate(10);
            }
            if($request->barcode != null){
                $data['products'] = Product::with(['brand', 'category', 'unit.related_unit'])
                    ->where('barcode',$request->barcode)
                    ->paginate(10);
            }
            if($request->category_id != null){
                $data['products'] = Product::with(['brand', 'category', 'unit.related_unit'])
                    ->where('category_id',$request->category_id)
                    ->paginate(10);
            }
            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)
                    ->paginate(10);
            }

        return view('backend.pages.product.sc-index', $data);
        
        }else{
            $data['products'] = Product::with(['brand', 'category', 'unit.related_unit'])->where('is_service',0)
                ->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('is_service',0)
                    ->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('is_service',0)
                    ->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('is_service',0)
                    ->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('is_service',0)
                    ->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();
            $variations = Variation::all();
            $sizes = ProductSize::all();
            $colors = ProductColor::all();
            $units = Unit::all();
            $suppliers = Supplier::all();
            return view('backend.pages.product.create', compact('brands','sizes','colors','variations', '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;
        $product->date = date('Y-m-d');
        $numberBarcode = rand(000000, 999999);
        if ($request->barcode == NULL) {
            $product->barcode = $numberBarcode;
        } else {
            $product->barcode = $request->barcode;
        }
        $product->is_service = 0;
        $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->has_serial = $request->has_serial;
        $product->sub_qty = $request->sub_qty;
        $product->purchase_price = $request->purchase_price;
        $product->selling_price = $request->selling_price;
        $product->retail_price = $request->retail_price;
        $product->wholesale_price = $request->wholesale_price;
        $product->diller_price = $request->diller_price;
        $product->status = $request->status;
        $product->description = $request->description;

        if ($product->save()) {
            $sizes = $request->size ?? [null]; // Default to null if no sizes
            $colors = $request->color ?? [null]; // Default to null if no colors
            foreach ($sizes as $size) {
                foreach ($colors as $color) {
                    $product->product_variations()->create([
                        'product_id' => $product->id,
                        'size_id' => $size,  // Can be null
                        'color_id' => $color, // Can be null
                    ]);
                }
            }
        }

        $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['variations'] = Variation::all();
        $data['sizes'] = ProductSize::all();
        $data['colors'] = ProductColor::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->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->retail_price = $request->retail_price;
        $product->wholesale_price = $request->wholesale_price;
        $product->diller_price = $request->diller_price;
        $product->status = $request->status;
        $product->description = $request->description;

        if ($product->save()) {
            $sizes = $request->size ?? [];
            $colors = $request->color ?? [];
        
            // Iterate through the larger of sizes or colors
            $maxCount = max(count($sizes), count($colors));
        
            for ($index = 0; $index < $maxCount; $index++) {
                $size = $sizes[$index] ?? null; // Get size or use null if not present
                $color = $colors[$index] ?? null; // Get color or use null if not present
        
                // Check if a variation exists for this size and update
                if ($size) {
                    $variation = $product->product_variations()->where('size_id', $size)->first();
        
                    if ($variation) {
                        $variation->update([
                            'color_id' => $color,
                        ]);
                    } else {
                        $product->product_variations()->create([
                            'size_id' => $size,
                            'color_id' => $color,
                        ]);
                    }
                } elseif ($color) {
                    // Create a variation for color without size
                    $product->product_variations()->create([
                        'size_id' => null, // No size provided
                        'color_id' => $color,
                    ]);
                }
            }
        }


        $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();
            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() {}
}
