<?php

namespace App\Http\Controllers\Product;

use App\Http\Controllers\Controller;
use App\Models\ProductImages;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ProductImageController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request,$id)
    {
        $images = ProductImages::where('product_id', $id)
        ->orderBy('product_images.priority' , 'ASC')
        ->get();
        return view('products.images.index', compact('images'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        $priority    = ProductImages::max('priority');
        $priority    = $priority != '' ? $priority + 1 : 1;
       
        return view('products.images.create',compact('priority'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'image'     => 'required',
            'file_type' => 'required',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        if ($request->hasFile('image')) {
            $url      = $request->product_id;
            $path     = "upload/products/".$url.'/'.date('Y').'/'.date('m');
            $response = uploadImage($path,$request->image);

            if ($response['status'] == true)
            {
                $image = $response['file_name'];
            }
            else
            {
                return response()->json([
                    'success' => false,
                    'message' => $response['message'],
                    'data'    => []
                ]);
            }
        }
        else
        {
            $image='';
        }

        $ProductImages =ProductImages::where(['product_id'=>$request->product_id])->first();
        $image_type    = $ProductImages?'otherimages':'cover';
        $is_default    = $ProductImages?0:1;

        $data['image_url']  = $image;
        $data['priority']   = $request->priority;
        $data['file_type']  = $request->file_type;
        $data['product_id'] = $request->product_id;
        $data['image_type'] = $image_type;
        $data['is_default'] = $is_default;

        $price = ProductImages::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Image has been created successfully',
            ]);
        }
        return redirect()->back()
            ->with('success','Image has been created successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $image = ProductImages::find($id);

        return view('products.images.edit', compact('image'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        
        $images = ProductImages::find($id);

        if (!$images) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => "Image not found!",
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', "Image not found!");
        }

        if ($request->hasFile('image')) {
            $url        = $images->product_id;
            $path       ="upload/products/".$url.'/'.date('Y').'/'.date('m');
            $response = uploadImage($path,$request->image);

            if ($response['status'] == true)
            {
                $image = $response['file_name'];
            }
            else
            {
                return response()->json([
                    'success' => false,
                    'message' => $response['message'],
                    'data'    => []
                ]);
            }
        }
        else
        {
            $image=$images->image_url;
        }

        $data['image_url'] = $image;
        $data['priority']  = $request->priority;
        $data['file_type'] = $request->file_type;
        $images->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Images has been Updated successfully',
            ]);
        }
        return redirect()->back()
            ->with('success','Images has been Updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $data = ProductImages::find($request->id);

        $data->delete();

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
            ]
        ]);
    }

    public function changeStatus(Request $request)
    {
       if ($request->ajax())
       {
           $data   = array('status' => $request->status);
           $Update = ProductImages::where('id', '=', $request->id)->update($data);

           if($Update){
               return response()->json([
                   'success'=>true,
                   'message'=>['Status successfully updated.'],
                   'data'=>[
                       'redirect'=>'/buckets/',
                       'reload'=>true,
                   ]
               ]);
           }
           else{
               return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
               ]);
           }
       }
    }

    public function changeIsDefault(Request $request)
    {
       if ($request->ajax())
       {
            if($request->status==1)
            {
                $Update = ProductImages::where('id', '!=', $request->id)->update(['is_default'=>0]);
                $Update = ProductImages::where('id', '=',  $request->id)->update(['is_default'=>1]);
            }
            else
            {
                $data   = array('is_default' => $request->status);
                $Update = ProductImages::where('id', '=', $request->id)->update($data);
            }
           

           if($Update){
               return response()->json([
                   'success'=>true,
                   'message'=>['Is Default Status successfully updated.'],
                   'data'=>[
                       'redirect'=>'',
                       'reload'=>true,
                   ]
               ]);
           }
           else{
               return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
               ]);
           }
       }
    }


    public function imageDownload($id)
    {
        // Retrieve the product image record by its ID
    $productImage = ProductImages::findOrFail($id);
    
    // Get the URL from the database
    $pdfUrl = $productImage->image_url; 

    // Extract file name from the URL
    $fileName = basename($pdfUrl);

    // Check if the file exists on S3
    if (Storage::disk('s3')->exists($fileName)) {
        // Generate a temporary download URL from S3
        $temporaryUrl = Storage::disk('s3')->temporaryUrl($fileName, now()->addMinutes(5));

        // Redirect to the temporary download URL
        return redirect($temporaryUrl);
    } else {
        // Handle the error if the file is not found
        return redirect()->back()->with('error', 'File not found!');
    }
    }

}
