<?php

namespace App\Http\Controllers\Setting;

use App\Http\Controllers\Controller;
use App\Models\ProductModel;
use App\Models\Brand;
use App\Models\ProductCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class ModelController extends Controller
{
    /**
     * Display a listing of the models.
     */
    public function index()
    {
        $models = ProductModel::with(['brand', 'category'])
                      ->orderBy('name')
                      ->paginate(15);
        
        return view('settings.models.index', compact('models'));
    }

    /**
     * Show the form for creating a new model.
     */
    public function create()
    {
        $brands = Brand::where('status', 1)->orderBy('name')->get(); // status ব্যবহার
        $categories = ProductCategory::where('is_active', 1)->orderBy('name')->get(); // is_active ব্যবহার
        
        return view('settings.models.create', compact('brands', 'categories'));
    }

    /**
     * Store a newly created model in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:models',
            'brand_id' => 'required|exists:brands,id',
            'category_id' => 'required|exists:product_categories,id',
            'specifications' => 'nullable|array',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048'
        ]);

        $data = [
            'name' => $request->name,
            'code' => $request->code,
            'brand_id' => $request->brand_id,
            'category_id' => $request->category_id,
            'specifications' => $request->specifications,
            'status' => $request->boolean('status', true),
            'created_by' => Auth::id()
        ];

        if ($request->hasFile('image')) {
            $image = $request->file('image');
            $imageName = time() . '_' . Str::slug($request->name) . '.' . $image->getClientOriginalExtension();
            $image->storeAs('public/models', $imageName);
            $data['image'] = $imageName;
        }

        ProductModel::create($data);

        return redirect()->route('settings.models.index')
            ->with('success', 'Model created successfully.');
    }

    /**
     * Show the form for editing the specified model.
     */
    public function edit(ProductModel $model)
    {
        $brands = Brand::where('status', 1)->orderBy('name')->get();
        $categories = ProductCategory::where('is_active', 1)->orderBy('name')->get();
        
        return view('settings.models.edit', compact('model', 'brands', 'categories'));
    }

    /**
     * Update the specified model in storage.
     */
    public function update(Request $request, ProductModel $model)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:models,code,' . $model->id,
            'brand_id' => 'required|exists:brands,id',
            'category_id' => 'required|exists:product_categories,id',
            'specifications' => 'nullable|array',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048'
        ]);

        $data = [
            'name' => $request->name,
            'code' => $request->code,
            'brand_id' => $request->brand_id,
            'category_id' => $request->category_id,
            'specifications' => $request->specifications,
            'status' => $request->boolean('status', true),
            'updated_by' => Auth::id()
        ];

        if ($request->hasFile('image')) {
            if ($model->image) {
                \Storage::delete('public/models/' . $model->image);
            }
            
            $image = $request->file('image');
            $imageName = time() . '_' . Str::slug($request->name) . '.' . $image->getClientOriginalExtension();
            $image->storeAs('public/models', $imageName);
            $data['image'] = $imageName;
        }

        $model->update($data);

        return redirect()->route('settings.models.index')
            ->with('success', 'Model updated successfully.');
    }

    /**
     * Remove the specified model from storage.
     */
    public function destroy(ProductModel $model)
    {
        if ($model->products()->count() > 0) {
            return back()->with('error', 'Cannot delete model with products.');
        }

        if ($model->image) {
            \Storage::delete('public/models/' . $model->image);
        }

        $model->delete();

        return redirect()->route('settings.models.index')
            ->with('success', 'Model deleted successfully.');
    }

    /**
     * Get models by brand (API)
     */
    public function getByBrand($brandId)
    {
        $models = ProductModel::where('brand_id', $brandId)
            ->where('status', 1)
            ->orderBy('name')
            ->get(['id', 'name', 'code']);
        
        return response()->json($models);
    }

    /**
     * Get models by category (API)
     */
    public function getByCategory($categoryId)
    {
        $models = ProductModel::where('category_id', $categoryId)
            ->where('status', 1)
            ->orderBy('name')
            ->get(['id', 'name', 'code']);
        
        return response()->json($models);
    }
}