<?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 App\Models\DeliveryFeeMaster;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;

class CategoryController extends Controller
{
  
    public function add_category_post(Request $request)
    {
        $rules = [
            'category_img'  => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
            'category_type' => 'required|in:1,2',
        ];
    
        if ($request->category_type == 1) {
            $rules['category_name'] = 'required|string|max:255';
        } elseif ($request->category_type == 2) {
            $rules['subcategory_name'] = 'required|string|max:255';
            $rules['link_to'] = 'required|exists:categories,id';
        }
    
        $messages = [
            'category_img.required'     => 'Please choose an image.',
            'category_name.required'    => 'The category name field is required.',
            'subcategory_name.required' => 'The subcategory name field is required when creating a subcategory.',
            'link_to.required'          => 'Please select a category to link the subcategory.',
        ];
    
        $validator = Validator::make($request->all(), $rules, $messages);
    
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }
    
        $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;
        }
    
        Category::create([
            'category_name'    => $request->category_type == 1 ? $request->category_name : null,
            'subcategory_name' => $request->category_type == 2 ? $request->subcategory_name : null,
            'link_to'          => $request->category_type == 2 ? $request->link_to : null,
            'category_img'     => $imagePath,
            'category_type'    => $request->category_type,
        ]);
    
        return redirect()->route('category')->with('success', 'Category added successfully.');
    }
    
    public function category_delete($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 delete_product($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 store_product(Request $request)
    {

        $validated = $request->validate([
            'category_id'    => 'required|exists:categories,id',
            'subcategory_id' => 'nullable|exists:categories,id',
            '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;
        }


        $category = Category::find($request->category_id);
        if (!$category) {
            return redirect()->back()->with('error', 'Selected category not found.');
        }
        $categoryName = $category->category_name;


        if ($request->filled('subcategory_id')) {
            $subcategory = Category::find($request->subcategory_id);


            if (!$subcategory || $subcategory->link_to != $category->id) {
                return redirect()->back()->with('error', 'Selected subcategory is invalid or does not belong to the selected category.');
            }
            $subcategoryName = $subcategory->subcategory_name;
        } else {
            $subcategoryName = null;
        }
        try {
            $product = Product::create([
                'category_id'      => $request->category_id,
                'subcategory_id'   => $request->subcategory_id,
                'image'            => $imagePath,
                'brand'            => $request->brand,
                'title'            => $request->title,
                'description'      => $request->description,
                'package'          => $request->package,
                'category_name'    => $categoryName,
                'subcategory_name' => $subcategoryName,
            ]);

            Log::info('Product Created:', $product->toArray());

            return redirect()->route('products')->with('success', 'Product added successfully!');
        } catch (\Exception $e) {
            Log::error('Error creating product:', ['error' => $e->getMessage()]);
            return redirect()->back()->with('error', 'An error occurred while adding the product.');
        }
    }
    public function getSubcategories(Request $request)
    {
        Log::info('Request parameters:', $request->all());

        $categoryId = $request->input('categoryId');

        if (empty($categoryId)) {

            return response()->json(['errormessage' => 'No categoryId provided'], 400);
        }
        $subcategories = Category::where('link_to', $categoryId)->get();
        Log::info($subcategories);
        return response()->json(['subcategories' => $subcategories]);
    }
   
        public function update_product(Request $request, $id)
        {
            $product = Product::findOrFail($id);
        
            $request->validate([
                'category_id'        => 'required',
                'title'              => 'required|max:255',
                'brand'              => 'required|max:255',
                'package'            => 'required|max:255',
                'description'        => 'required',
                'unit.*'             => 'required|max:255',
                'mrp.*'              => 'required|numeric',
                'price.*'            => 'required|numeric',
                'discount.*'         => 'nullable|numeric',
                'spec_title.*'       => 'required|max:255',
                'spec_description.*' => 'required|max:1000',
                'image'              => 'nullable|image|mimes:jpeg,png,jpg|max:2048'
            ]);
        
          
            $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->title            = $request->input('title');
            $product->description      = $request->input('description');
            $product->brand            = $request->input('brand');
            $product->package          = $request->input('package');
            $product->category_id      = $request->input('category_id');
            $product->subcategory_name = $request->input('subcategory_name');
            $product->image            = $imagePath;
            $product->save();
        
          
            $product->variants()->delete(); 
        
           
            $units            = $request->input('unit', []);
            $mrps             = $request->input('mrp', []);
            $prices           = $request->input('price', []);
            $discounts        = array_pad($request->input('discount', []), count($units), 0);
            $specTitles       = $request->input('spec_title', []);
            $specDescriptions = $request->input('spec_description', []);
        
          
            while (count($specTitles) < count($units)) {
                $specTitles[] = '';
            }
            while (count($specDescriptions) < count($units)) {
                $specDescriptions[] = '';
            }
        
            Log::info('Units: ' . print_r($units, true));
            Log::info('MRPs: ' . print_r($mrps, true));
            Log::info('Prices: ' . print_r($prices, true));
            Log::info('Discounts: ' . print_r($discounts, true));
            Log::info('Spec Titles: ' . print_r($specTitles, true));
            Log::info('Spec Descriptions: ' . print_r($specDescriptions, true));
        
            $variantCount = count($units);
        
            if ($variantCount === count($mrps) && $variantCount === count($prices) && $variantCount === count($specTitles) && $variantCount === count($specDescriptions)) {
                foreach ($units as $index => $unit) {
                    $product->variants()->create([
                        'unit'        => $unit,
                        'mrp'         => $mrps[$index],
                        'price'       => $prices[$index],
                        'discount'    => $discounts[$index],
                        'title'       => $specTitles[$index],
                        'description' => $specDescriptions[$index]
                    ]);
                }
            } else {
                return redirect()->back()->withErrors('The input arrays must have the same number of elements.');
            }
        
            return redirect()->route('products')->with('success', 'Product updated successfully!');
        }
        
}