<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\HomepageCacheHelper;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\Category;
use App\Models\CustomOffer;
use Toastr;

class InhouseProductController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:product-list|product-create|product-edit|product-delete', ['only' => ['index','show']]);
    }

    /**
     * Display all inhouse products (products without vendor_id)
     */
    public function index(Request $request)
    {
        // Show only inhouse products (vendor_id is null)
        $query = Product::orderBy('id','DESC')
            ->orderBy('id','DESC')
            ->with('image','category', 'offers');

        if ($request->keyword) {
            $query->where('name', 'LIKE', '%' . $request->keyword . "%");
        }

        if ($request->category_id) {
            $query->where('category_id', $request->category_id);
        }

        if ($request->status !== null) {
            $query->where('status', $request->status);
        }

        $data = $query->paginate(20);
        $categories = Category::where('parent_id', 0)->where('status', 1)->select('id', 'name')->get();
        $custom_offers = CustomOffer::active()->orderBy('sort_order')->get();
        
        return view('backEnd.inhouse_product.index', compact('data', 'categories', 'custom_offers'));
    }

    /**
     * Bulk Assign Products to Custom Offers
     */
    public function bulk_assign_offers(Request $request)
    {
        $request->validate([
            'product_ids' => 'required|array',
            'offer_ids' => 'required|array',
        ]);

        $products = Product::whereIn('id', $request->product_ids)->get();

        if ($products->isEmpty()) {
            return response()->json([
                'status' => 'error', 
                'message' => 'No valid products found for assignment'
            ]);
        }

        foreach ($products as $product) {
            // Use syncWithoutDetaching to add to existing offers if any
            $product->offers()->syncWithoutDetaching($request->offer_ids);
            
            // Clear cache for each product to reflect changes on frontend
            \Illuminate\Support\Facades\Cache::forget('product_details_' . $product->slug);
        }

        HomepageCacheHelper::clear();

        return response()->json([
            'status' => 'success', 
            'message' => count($products) . ' products assigned to ' . count($request->offer_ids) . ' offers successfully'
        ]);
    }

    /**
     * Show single product details
     */
    public function show($id)
    {
        $product = Product::with('image','images','category','subcategory','childcategory','brand','colors','sizes')
            ->findOrFail($id);
            
        return view('backEnd.inhouse_product.show', compact('product'));
    }
}
