<?php

namespace App\Http\Controllers\Backend;

use App\Helpers\CoreConstants;
use App\Http\Controllers\Controller;
use App\Models\Gallary;
use App\Models\Menu;
use App\Models\Product;
use App\Models\Tag;
use App\Models\Variant;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;

class ProductController extends Controller
{
    public function index()
    {
        $data['PageTitle'] = 'Add Product';
        $data['products'] = Product::with('variants')->latest()->get();
        $data['parentProductShowClass'] = 'show';
        $data['allProductActiveClass'] = 'active';
        return view('backend.product.index')->with($data);
    }

    public function create()
    {
        $data['PageTitle'] = 'Add Product';
        $data['subMenu'] =  Menu::whereNotNull('parent_id')->get();
        $data['menus'] = Menu::whereNull('parent_id')->get();
        $data['parentProductShowClass'] = 'show';
        $data['addProductActiveClass'] = 'active';
        return view('backend.product.create')->with($data);
    }

    public function store(Request $request)
    {
        DB::beginTransaction();
        try {
            $request->validate([
                'name' => 'required|string|max:255',
                'description' => 'required|string',
                'detail' => 'required|string',
                'material' => 'required|string',
                'care' => 'required|string',
                'price' => 'required|numeric',
                'discount_price' => 'nullable|numeric',
                'stock' => 'required|numeric',
                'brand_name' => 'nullable|string',
                'sku' => 'nullable|string',
                'status' => 'required|in:in-stock,out-of-stock',
                'image' => 'required|image|mimes:jpeg,png,jpg,webp|max:2048',
            ]);

            // ✅ Stock safe handling (STORE)
            $manualStock = (int) $request->stock;

            $sizes = (array) $request->input('variation.size', []);
            $qtys  = (array) $request->input('variation.quantity', []);

            $variantRows  = [];
            $variantTotal = 0;

            foreach ($sizes as $i => $size) {
                $size = trim((string) $size);
                if ($size === '') continue; // ✅ empty size ignore

                $q = (int) ($qtys[$i] ?? 0);
                if ($q < 0) $q = 0;

                $variantRows[] = ['size' => $size, 'stock' => $q];
                $variantTotal += $q;
            }

            $useVariants = count($variantRows) > 0;

            $product = new Product();
            $product->name = $request->name;
            $product->title = $request->title;
            $product->description = $request->description;
            $product->detail = $request->detail;
            $product->matetial = $request->material;
            $product->care = $request->care;
            $product->price = $request->price;
            $product->discount_price = $request->discount_price;

            // ✅ variant থাকলে total variant stock, না থাকলে manual stock
            $product->stock = $useVariants ? $variantTotal : $manualStock;

            $product->category_id = $request->category_id;
            $product->subcategory_id = $request->subcategory_id;
            $product->brand_name = $request->brand_name;
            $product->sku = $request->sku;
            $product->product_code = $request->product_code;
            $product->status = $request->status;
            $product->alt = $request->alt;
            $product->sold_count = '0';

            $slug = Str::slug($request->title, '-');
            $product->slug = $slug;

            if ($request->hasFile('image')) {
                $image = $request->file('image');
                $orginalName = time() . '.' . $image->getClientOriginalName();
                $fileName = pathinfo($orginalName, PATHINFO_FILENAME);
                $extension = pathinfo($orginalName, PATHINFO_EXTENSION);
                $imageName = preg_replace('/\s+/', '', $fileName);
                $file_name = preg_replace('/[^A-Za-z0-9\-]/', '', $imageName);
                $name = $file_name . '.' . $extension;
                $store = $image->storeAs('upload', $name, 'public');
                $product->thumbnail = $store;
            }

            $product->save();

            // ✅ Only insert variants if we actually have valid variant rows
            if ($product && $useVariants) {
                $insertData = [];
                foreach ($variantRows as $row) {
                    $insertData[] = [
                        'product_id' => $product->id,
                        'size'       => $row['size'],
                        'stock'      => $row['stock'],
                    ];
                }
                Variant::insert($insertData);
            }

            $tagsJson = $request->tags[0] ?? '[]';
            $tags = json_decode($tagsJson, true);
            if (!is_array($tags)) {
                $tags = [];
            }

            foreach ($tags as $tag) {
                Tag::create([
                    'product_id' => $product->id,
                    'tag' => $tag['value'],
                ]);
            }

            if ($request->hasFile('gallary_image')) {
                $images = $request->file('gallary_image');
                foreach ($images as $file) {
                    $orginalName = time() . '.' . $file->getClientOriginalName();
                    $fileName = pathinfo($orginalName, PATHINFO_FILENAME);
                    $extension = pathinfo($orginalName, PATHINFO_EXTENSION);
                    $imageName = preg_replace('/\s+/', '', $fileName);
                    $file_name = preg_replace('/[^A-Za-z0-9\-]/', '', $imageName);
                    $image_name = $file_name . '.' . $extension;

                    $image_store = $file->storeAs('gallary_image', $image_name, 'public');

                    Gallary::create([
                        'product_id' => $product->id,
                        'image' => $image_store,
                    ]);
                }
            }

            DB::commit();
            return redirect()->route('admin.product.index')->with('success', 'Product created successfully!');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Error creating product', ['error' => $e->getMessage()]);
            return redirect()->back()->with('error', "spmething went wrong!");
        }
    }

    public function show(Product $product)
    {
        //
    }

    public function edit(Product $product)
    {
        $data['PageTitle'] = 'Add Product';
        $data['subMenu'] =  Menu::whereNotNull('parent_id')->get();
        $data['menus'] = Menu::whereNull('parent_id')->get();
        $product->load(['galleries', 'tags', 'variants']);
        $data['product'] = $product;
        $data['parentProductShowClass'] = 'show';
        $data['ProductActiveClass'] = 'active';
        return view('backend.product.edit')->with($data);
    }

    public function update(Request $request, Product $product)
    {
        DB::beginTransaction();
        try {
            $request->validate([
                'name' => 'required|string|max:255',
                'description' => 'required|string',
                'detail' => 'required|string',
                'material' => 'required|string',
                'care' => 'required|string',
                'price' => 'required|numeric',
                'discount_price' => 'nullable|numeric',
                'stock' => 'required|numeric',
                'brand_name' => 'nullable|string',
                'sku' => 'nullable|string',
                'alt' => 'required|string',
                'status' => 'required|in:in-stock,out-of-stock',
                'image' => 'image|mimes:jpeg,png,jpg,webp|max:2048',
            ]);

            // ✅ Stock safe handling (UPDATE)
            $manualStock = (int) $request->stock;

            $sizes = (array) $request->input('variation.size', []);
            $qtys  = (array) $request->input('variation.quantity', []);

            $variantRows  = [];
            $variantTotal = 0;

            foreach ($sizes as $i => $size) {
                $size = trim((string) $size);
                if ($size === '') continue; // ✅ empty size ignore

                $q = (int) ($qtys[$i] ?? 0);
                if ($q < 0) $q = 0;

                $variantRows[] = ['size' => $size, 'stock' => $q];
                $variantTotal += $q;
            }

            $useVariants = count($variantRows) > 0;

            $product->name = $request->name;
            $product->title = $request->title;
            $product->description = $request->description;
            $product->detail = $request->detail;
            $product->matetial = $request->material;
            $product->care = $request->care;
            $product->price = $request->price;
            $product->discount_price = $request->discount_price;

            // ✅ variant থাকলে total variant stock, না থাকলে manual stock
            $product->stock = $useVariants ? $variantTotal : $manualStock;

            $product->category_id = $request->category_id;
            $product->subcategory_id = $request->subcategory_id;
            $product->brand_name = $request->brand_name;
            $product->sku = $request->sku;
            $product->product_code = $request->product_code;
            $product->status = $request->status;
            $product->alt = $request->alt;
            $product->sold_count = '0';

            $slug = Str::slug($request->title, '-');
            $product->slug = $slug;

            if ($request->hasFile('image')) {
                $image = $request->file('image');
                $orginalName = time() . '.' . $image->getClientOriginalName();
                $fileName = pathinfo($orginalName, PATHINFO_FILENAME);
                $extension = pathinfo($orginalName, PATHINFO_EXTENSION);
                $imageName = preg_replace('/\s+/', '', $fileName);
                $file_name = preg_replace('/[^A-Za-z0-9\-]/', '', $imageName);
                $name = $file_name . '.' . $extension;
                $store = $image->storeAs('upload', $name, 'public');
                if ($product->thumbnail && Storage::disk('public')->exists($product->thumbnail)) {
                    Storage::disk('public')->delete($product->thumbnail);
                }
                $product->thumbnail = $store;
            }

            $product->save();

            // ✅ Variants update: always clear old, insert only valid ones
            if ($product) {
                $product->variants()->delete();

                if ($useVariants) {
                    $insertData = [];
                    foreach ($variantRows as $row) {
                        $insertData[] = [
                            'product_id' => $product->id,
                            'size'       => $row['size'],
                            'stock'      => $row['stock'],
                        ];
                    }
                    Variant::insert($insertData);
                }
            }

            $tagsJson = $request->tags[0] ?? '[]';
            $tags = json_decode($tagsJson, true);
            if ($product) {
                $product->tags()->delete();
                if (!is_array($tags)) {
                    $tags = [];
                }
                foreach ($tags as $tag) {
                    Tag::create([
                        'product_id' => $product->id,
                        'tag' => $tag['value'],
                    ]);
                }
            }

            if ($product) {
                if ($request->hasFile('gallary_image')) {
                    $galleries = Gallary::where('product_id', $product->id)->get();
                    foreach ($galleries as $image) {
                        if ($image->image && Storage::disk('public')->exists($image->image)) {
                            Storage::disk('public')->delete($image->image);
                        }
                    }
                    $product->galleries()->delete();

                    $images = $request->file('gallary_image');
                    foreach ($images as $file) {
                        $orginalName = time() . '.' . $file->getClientOriginalName();
                        $fileName = pathinfo($orginalName, PATHINFO_FILENAME);
                        $extension = pathinfo($orginalName, PATHINFO_EXTENSION);
                        $imageName = preg_replace('/\s+/', '', $fileName);
                        $file_name = preg_replace('/[^A-Za-z0-9\-]/', '', $imageName);
                        $image_name = $file_name . '.' . $extension;
                        $image_store = $file->storeAs('gallary_image', $image_name, 'public');

                        Gallary::create([
                            'product_id' => $product->id,
                            'image' => $image_store,
                        ]);
                    }
                }
            }

            DB::commit();
            return redirect()->route('admin.product.index')->with('success', CoreConstants::UPLOADED_SUCCESSFULLY);
        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->back()->with('error', 'something went wrong');
        }
    }

    public function destroy(Product $product)
    {
        if ($product->thumbnail && Storage::disk('public')->exists($product->thumbnail)) {
            Storage::disk('public')->delete($product->thumbnail);
        }

        $galleries = Gallary::where('product_id', $product->id)->get();
        foreach ($galleries as $image) {
            if ($image->image && Storage::disk('public')->exists($image->image)) {
                Storage::disk('public')->delete($image->image);
            }
        }
        $product->tags()->delete();
        $product->galleries()->delete();
        $product->variants()->delete();
        $product->delete();
        return redirect()->route('admin.product.index')->with('success', CoreConstants::DELETED_SUCCESSFULLY);
    }

    public function searchr(Request $request)
    {
        if ($request->has('term')) {
            $term = $request->input('term');
            $products = Product::where('name', 'LIKE', '%' . $term . '%')
                ->select('id', 'name', 'slug')
                ->get();

            $return_arr = [];
            foreach ($products as $product) {
                $return_arr[] = [
                    'id' => $product->id,
                    'label' => $product->name,
                    'value' => $product->name,
                    'slug' => $product->slug,
                ];
            }
            return response()->json($return_arr);
        }
    }
}
