<?php

namespace App\Http\Controllers\Reseller;

use App\Models\LandingPage;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\LandingPageProductImage;

class ImageController extends Controller
{
    public function index($slug)
    {
        $page = LandingPage::where('status', 1)->where('page_slug', $slug)->firstOrFail();
        $images = LandingPageProductImage::where('landing_page_id', $page->id)->with('landingPage')->orderby('id', 'desc')->get();
        return response()->json([
            'images' => $images,
            'success' => true,
        ]);
    }

    public function store(Request $request)
    {
        // return $request->all();
        $this->validate($request, [
            'landing_page_id' => 'required',
        ]);
        $image = new LandingPageProductImage();
        $image->reseller_id = session()->get('reseller')['id'];
        $image->landing_page_id = $request->landing_page_id;
        if ($request->hasFile('image')) {
            $path = $request->file('image')->store('images/landing_image', 'public');
            $image->image = $path;
        }
        $image->save();
        return response()->json([
            'success' => true,
            'message' => 'image added successfully'
        ]);
        
    }

    

    public function status($id)
    {
        $image = LandingPageProductImage::find($id);
        if ($image->status == 1) {
            $image->status = 0;
            $image->save();
        }else{
            $image->status = 1;
            $image->save();
        }

        return response()->json([
            'success' => true,
            'message' => 'image status updated'
        ]);
    }


    public function edit($id)
    {
        $image = LandingPageProductImage::with('landingPage')->find($id);
        return response()->json([
            'success' => true,
            'image' => $image
        ]);
    }




    public function update(Request $request, $id)
    {

        $this->validate($request, [
            'landing_page_id' => 'required',
        ]);
        $image = LandingPageProductImage::find($id);
        $image->landing_page_id = $request->landing_page_id;
        $image->reseller_id = session()->get('reseller')['id'];
        if ($request->hasFile('image')) {
            $path = $request->file('image')->store('images/landing_image', 'public');
            $image->image = $path;
        }
        $image->save();
        return response()->json([
            'success' => true,
            'message' => 'image update successfully'
        ]);
        
    }



    public function delete($id)
    {
        $image = LandingPageProductImage::findOrFail($id);
        $image->delete();
        return response()->json([
            'success' => true,
            'message' => 'image deleted successfully'
        ]);
    }
}
