<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Repositories\ProductRepository;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    protected $productRepo;
    public function __construct(ProductRepository $productRepository)
    {
        $this->productRepo = $productRepository;
    }


    public function index()
    {

        return $this->productRepo->indexPage();
    }

    public function createPage()
    {
        return $this->productRepo->createPage();

    }

    public function edit($id)
    {
        return $this->productRepo->editPage($id);

    }

    public function store(Request $request)
    {
        // dd($request->all());
        $request->validate([
            'name' => 'required|max:255',
            'description' => 'required',
            'price' => 'required',
            'category_id' => 'required',
            'product_image' => 'required|image',
        ]);
        try {
            $data = $request->except('colour_id');
            $colorIds = $request->input('colour_id');
            $product = $this->productRepo->create($data);
            if ($request->hasFile('product_image')) {
                $product->addMediaFromRequest('product_image')->toMediaCollection('product_image');
            }

            if ($request->hasFile('product_gallery_images')) {
                foreach ($request->file('product_gallery_images') as $image) {
                    $product->addMedia($image)->toMediaCollection('product_gallery_images');
                }
            }

            $product->colors()->sync($colorIds);
            return redirect()->route('admin.product.list')->with('success', 'Product Successfully Added');
        } catch (\Exception $e) {
            dd($e->getMessage());
            return redirect()->back()->with('error', $e->getMessage());
        }

    }

    public function update(Request $request, $id)
    {
        // dd($request->all());
        $request->validate([
            'name' => 'required|max:255',
            'description' => 'required',
            'category_id' => 'required',
            'price' => 'required',
        ]);
        try {
            $data = $request->except('colour_id');
            $colorIds = $request->input('colour_id');
            $update = $this->productRepo->update($data, $id);
            $update->colors()->sync($colorIds);
            if ($request->hasFile('product_image')) {
                $update->clearMediaCollection('product_image');
                $update->addMediaFromRequest('product_image')->toMediaCollection('product_image');
            }

            // Handle Gallery Images
            // 1. Add New Gallery Images
            if ($request->hasFile('product_gallery_images')) {
                foreach ($request->file('product_gallery_images') as $image) {
                    $update->addMedia($image)->toMediaCollection('product_gallery_images');
                }
            }

            // 2. Change Existing Images
            if ($request->hasFile('change_images')) {
                foreach ($request->file('change_images') as $index => $image) {
                    // Get existing media item by index
                    $existingMediaItems = $update->getMedia('product_gallery_images');
                    if (isset($existingMediaItems[$index])) {
                        $existingMediaItems[$index]->delete();
                    }
                    $update->addMedia($image)->toMediaCollection('product_gallery_images');
                }
            }

            // 3. Remove Images
            if ($request->has('remove_images')) {
                foreach ($request->remove_images as $imageId) {
                    $mediaItem = $update->getMedia('product_gallery_images')->firstWhere('id', $imageId);
                    if ($mediaItem) {
                        $mediaItem->delete();
                    }
                }
            }
            return redirect()->route('admin.product.list')->with('success', 'Product Successfully Updated');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());

        }

    }

    public function delete(Request $request)
    {
        $this->productRepo->delete($request->id);
        return response()->json(['success' => 'Record successfully deleted!']);

    }
}
