<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ProductVarient;
use Illuminate\Http\Request;
use App\Models\Category;
use App\Models\Product;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;

class CategoryController extends Controller
{
    public function storeCategory(Request $request)
    {
        $validatedData = $request->validate([
            'town_id' => 'required|exists:delivery_fee_masters,id',
              // 'town_name' => 'required|exists:delivery_fee_masters,town',
            'category_img'  => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'category_name' => 'required|string|max:255',
            'category_type' => 'required|in:1,2',
            'link_to'       => 'nullable',
        ]);

        $imagePath = null;
        if ($request->hasFile('category_img')) {
            $fileName        = time() . '_' . $request->file('category_img')->getClientOriginalName();
            $destinationPath = public_path('assets/images/products');
            $request->file('category_img')->move($destinationPath, $fileName);
            $imagePath = 'assets/images/products/' . $fileName;
            Log::info('Image uploaded to: ' . $imagePath);
        }

        $category          = new Category();
        $category->town_id = $request->town_id;
        // $category->town = $request->town;
        $category->name        = $request->category_name;
        $category->type        = $request->category_type;
        $category->subcategory = $request->link_to;
        $category->image       = $imagePath;
        Log::info('Category data:', $category->toArray());
        $category->save();

        return redirect()->route('category')->with('successmessage', 'Category added successfully!');
    }
    public function destroy($id)
    {
        $category = Category::findOrFail($id);
        if($category){
        $category->delete();
        return redirect()->back()->with('successmessage', 'Category deleted successfully.');
    }
    return redirect()->back()->with('errormessage','Error not found');
}

    public function product_delete($id)
    {
        $product = Product::findOrFail($id);
        if($product){
        $product->delete();
        return redirect()->back()->with('successmessage', 'Product deleted successfully.');
    }
    return redirect()->back()->with('errormessage','Error not found');
}

    public function storeProduct(Request $request)
    {
        $request->validate([
            'category_id'      => 'required|exists:categories,id',
            'subcategory_name' => 'nullable|string|max:255',
            'image'            => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'brand'            => 'required|string|max:255',
            'title'            => 'required|string|max:255',
            'description'      => 'nullable|string',
            'package'          => 'nullable|string|max:255',
        ]);

        $imagePath = null;
        if ($request->hasFile('image')) {
            $fileName = time() . '_' . $request->file('image')->getClientOriginalName();
            $destinationPath = public_path('assets/images/products');
            $request->file('image')->move($destinationPath, $fileName);
            $imagePath = 'assets/images/products/' . $fileName;
        }

        Product::create([
            'category_id'      => $request->category_id,
            'subcategory_name' => $request->subcategory_name,
            'image'            => $imagePath,
            'brand'            => $request->brand,
            'title'            => $request->title,
            'description'      => $request->description,
            'package'          => $request->package,
        ]);

        return redirect()->route('products')->with('successmessage', 'Product added successfully!');
    }

    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'category_id'        => 'required|exists:categories,id',
            'subcategory_name'   => 'required|string',
            'image'              => 'nullable|image|mimes:png,jpg,jpeg|max:2048',
            'brand'              => 'nullable|string',
            'title'              => 'required|string',
            'description'        => 'nullable|string',
            'package'            => 'nullable|string',
            'unit.*'             => 'nullable|string',
            'discount.*'         => 'nullable|numeric',
            'mrp.*'              => 'nullable|numeric',
            'price.*'            => 'nullable|numeric',
            'spec_title.*'       => 'nullable|string',
            'spec_description.*' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $product   = Product::findOrFail($id);
        $imagePath = $product->image;

        if ($request->hasFile('image')) {
            if ($imagePath && file_exists(public_path($imagePath))) {
                unlink(public_path($imagePath));
            }
            $fileName = time() . '_' . $request->file('image')->getClientOriginalName();
            $destinationPath = public_path('assets/images/products');
            $request->file('image')->move($destinationPath, $fileName);
            $imagePath = 'assets/images/products/' . $fileName;

            Log::info('Image uploaded to: ' . $imagePath);
        }

        $product->category_id      = $request->input('category_id');
        $product->subcategory_name = $request->input('subcategory_name');
        $product->brand            = $request->input('brand');
        $product->title            = $request->input('title');
        $product->description      = $request->input('description');
        $product->package          = $request->input('package');
        $product->image            = $imagePath;
        $product->save();


        $units     = $request->input('unit', []);
        $discounts = $request->input('discount', []);
        $mrps      = $request->input('mrp', []);
        $prices    = $request->input('price', []);

        $maxLength = max(count($units), count($discounts), count($mrps), count($prices));

        $units     = array_pad($units, $maxLength, null);
        $discounts = array_pad($discounts, $maxLength, null);
        $mrps      = array_pad($mrps, $maxLength, null);
        $prices    = array_pad($prices, $maxLength, null);

        ProductVarient::where('product_id', $product->id)->delete();
        foreach ($units as $index => $unit) {
            if ($unit) {
                ProductVarient::create([
                    'product_id' => $product->id,
                    'unit'       => $unit,
                    'discount'   => $discounts[$index] ?? null,
                    'mrp'        => $mrps[$index] ?? null,
                    'price'      => $prices[$index] ?? null,
                    'title'      => 'Variant ' . ($index + 1),
                ]);
            }
        }

        $specTitles       = $request->input('spec_title', []);
        $specDescriptions = $request->input('spec_description', []);


        $specifications = array_map(null, $specTitles, $specDescriptions);

        ProductVarient::where('product_id', $product->id)->delete();

        foreach ($specifications as $spec) {
            if ($spec[0]) {
                ProductVarient::create([
                    'product_id'  => $product->id,
                    'unit'        => $unit,
                    'discount'    => $discounts[$index] ?? null,
                    'mrp'         => $mrps[$index] ?? null,
                    'price'       => $prices[$index] ?? null,
                    'title'       => $spec[0],
                    'description' => $spec[1] ?? null,
                ]);
            }
        }

        return redirect()->route('products')
            ->with('success', 'Product updated successfully!');
    }

}