<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Products;
use App\Models\ProductImage;
use App\Models\Category;
use App\Models\SubCategory;
use App\Models\Country;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Yajra\DataTables\Facades\DataTables;

class ProductController extends Controller
{
    public function index()
    {
        return view('admin.product', [
            'countries' => Country::all()
        ]);
    }

    public function getProducts(Request $request)
    {
        if ($request->ajax()) {
            $data = Products::with(['category', 'subCategory', 'images', 'country'])->get();

            return DataTables::of($data)
                ->addIndexColumn()
                ->addColumn('category', fn($row) => $row->category->name ?? '-')
                ->addColumn('subcategory', fn($row) => $row->subCategory->name ?? '-')
                ->addColumn('country', fn($row) => $row->country->name ?? '-')
                ->addColumn('images', function ($row) {
                    if ($row->images && count($row->images)) {
                        $imgTag = '';
                        foreach ($row->images as $img) {
                            $imgTag .= '<img src="' . asset('uploads/products/' . $img->image) . '" width="50" height="50" style="margin:2px;">';
                        }
                        return $imgTag;
                    }
                    return 'No Image';
                })
                ->addColumn('is_trending', fn($row) => $row->is_trending ? '<span class="badge bg-warning">Yes</span>' : 'No')
                ->addColumn('status', fn($row) => $row->status ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-danger">Inactive</span>')
                ->addColumn('action', function ($row) {
                    return '
                        <button class="btn btn-sm btn-primary editproduct" data-id="' . $row->id . '">Edit</button>
                        <button class="btn btn-sm btn-danger deleteproduct" data-id="' . $row->id . '">Delete</button>
                    ';
                })
                ->rawColumns(['images', 'is_trending', 'status', 'action'])
                ->make(true);
        }

        return view('admin.products');
    }

    public function store(Request $request)
    {
        $request->validate([
            'category_id' => 'required|exists:categories,id',
            'sub_category_id' => 'nullable|exists:sub_categories,id',
            'country_id' => 'required|exists:countries,id',
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'price' => 'required|numeric|min:0',
            'discount_price' => 'nullable|numeric|min:0',
            'stock' => 'required|integer|min:0',
            'is_trending' => 'nullable|boolean',
            'images.*' => 'image|mimes:jpg,jpeg,png|max:2048',
        ]);

        $slug = Str::slug($request->name);
        $originalSlug = $slug;
        $counter = 1;
        while (Products::where('slug', $slug)->exists()) {
            $slug = $originalSlug . '-' . $counter++;
        }

        $product = Products::create([
            'category_id' => $request->category_id,
            'sub_category_id' => $request->sub_category_id,
            'country_id' => $request->country_id,
            'name' => ucfirst($request->name),
            'slug' => $slug,
            'description' => $request->description,
            'price' => $request->price,
            'discount_price' => $request->discount_price,
            'stock' => $request->stock,
            'is_trending' => $request->is_trending ?? 0,
            'status' => 1,
        ]);

        if ($request->hasFile('images')) {
            foreach ($request->file('images') as $file) {
                $name = time() . '-' . rand(100, 999) . '.' . $file->extension();
                $file->move(public_path('uploads/products'), $name);
                ProductImage::create([
                    'product_id' => $product->id,
                    'image' => $name
                ]);
            }
        }

        return response()->json(['success' => 'Product added successfully!']);
    }

    public function destroy($id)
    {
        $product = Products::findOrFail($id);
        foreach ($product->images as $img) {
            $path = public_path('uploads/products/' . $img->image);
            if (File::exists($path)) File::delete($path);
            $img->delete();
        }
        $product->delete();
        return response()->json(['success' => 'Product deleted successfully.']);
    }

    public function show($id)
    {
        $product = Products::with(['images', 'country'])->findOrFail($id);
        return response()->json($product);
    }

    public function update(Request $request, $id)
    {
        $product = Products::findOrFail($id);

        $request->validate([
            'name' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id',
            'sub_category_id' => 'nullable|exists:sub_categories,id',
            'country_id' => 'required|exists:countries,id',
            'price' => 'required|numeric|min:0',
            'discount_price' => 'nullable|numeric|min:0',
            'stock' => 'required|integer|min:0',
            'is_trending' => 'nullable|boolean',
            'images.*' => 'image|mimes:jpg,jpeg,png|max:2048',
        ]);

        $product->update([
            'category_id' => $request->category_id,
            'sub_category_id' => $request->sub_category_id,
            'country_id' => $request->country_id,
            'name' => ucfirst($request->name),
            'description' => $request->description,
            'price' => $request->price,
            'discount_price' => $request->discount_price,
            'stock' => $request->stock,
            'is_trending' => $request->is_trending ?? 0,
        ]);

        if ($request->hasFile('images')) {
            foreach ($request->file('images') as $file) {
                $name = time() . '-' . rand(100, 999) . '.' . $file->extension();
                $file->move(public_path('uploads/products'), $name);
                ProductImage::create([
                    'product_id' => $product->id,
                    'image' => $name
                ]);
            }
        }

        return response()->json(['success' => 'Product updated successfully!']);
    }
}
