<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Advertisement;
use App\Models\Position;
use App\Models\Page;
// use Yajra\DataTables\Facades\Datatables;
use Yajra\DataTables\Html\Builder;
use Validator;
use File;
use ImgUploader;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use DataTables;

class AdvertisementController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth:admin')->except('AdPositionCheck');
    }
    
    public function index()
    {
        return view('admin.advertisements.index');
    }

    public function getAdData(Request $request)
    {
        if ($request->ajax()) {
            $data = Advertisement::orderByDesc('created_at')
                ->join('pages', 'advertisements.page', '=', 'pages.id')
                ->join('positions', 'advertisements.position', '=', 'positions.id')
                ->select('advertisements.*', 'pages.page_name', 'positions.position')
                ->get();
                
            return DataTables::of($data)
                ->addIndexColumn()
                ->addColumn('page', function ($row) {
                    return $row->page_name;
                })
                ->addColumn('position', function ($row) {
                    return $row->position;
                })
                ->addColumn('image', function ($row) {
                    $imageUrl = asset($row->image);
                    return $imageUrl;
                })
                             
                ->addColumn('action', function ($row) {
                    $btn = ' <td class="text-end"><a href="' . route('admin.advertisements.edit', $row->id) . '" class="btn btn-outline-info btn-rounded"><i class="fas fa-pen"></i></a><form action="'. route('admin.advertisements.destroy', $row->id) .'" method="POST" style="display:inline">
                    ' .csrf_field() .'
                    ' .method_field('DELETE').'
                    <button type="submit" class="btn btn-outline-danger btn-rounded">
                        <i class="fas fa-trash"></i>
                    </button>
                </form>
                            </td>';
    
                    return $btn;
                })
                ->rawColumns(['action'])
                ->make(true);
                
        }
    }
    
    public function create()
    {
        $positions = Position::all();
        $pages = Page::all();
        return view('admin.advertisements.create', compact('positions','pages'));
    }


    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'page' => 'required',
            'position' => 'required',
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'redirection_url' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect()->route('advertisements.create')
                ->withErrors($validator)
                ->withInput();
        }

        // Get the uploaded image
        $image = $request->file('image');

        // Check if the image is valid
        if (!$image->isValid()) {
            return redirect()->route('advertisements.create')
                ->with('danger', 'Invalid image uploaded.');
        }

        $imagePath = $this->uploadImage($image);

        try {
            Advertisement::create([
                'name' => $request->name,
                'image' => $imagePath,
                'page' => $request->page,
                'position' => $request->position,
                'redirection_url' => $request->redirection_url,
            ]);

            return redirect()->route('admin.advertisements.index')->with('success', 'Advertisement created.');
        } catch (\Exception $e) {
            // Error occurred while saving, delete the image
            $this->deleteImage($imagePath);

            return redirect()->route('admin.advertisements.index')->with('error', 'Error occurred while saving. Please try again.');
        }
    }


    public function edit($id)
    {
        $advertisement = Advertisement::findOrFail($id);
        $positions = Position::all();
        $pages = Page::all();
        $imageUrl = asset('adImages/' . $advertisement->image);
        return view('admin.advertisements.edit', compact('advertisement', 'positions','pages', 'imageUrl'));
    }

    public function update(Request $request, Advertisement $advertisement)
    {
        $request->validate([
            'page' => 'required',
            'position' => 'required',
            'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);
    
        if ($request->hasFile('image')) {
            // Get the uploaded image
            $image = $request->file('image');
    
            // Check if the image is valid
            if (!$image->isValid()) {
                return redirect()->back()->with('danger', 'Invalid image uploaded.');
            }
    
            // Delete the existing image
            $this->deleteImage($advertisement->image);
    
            // Upload the new image
            $imagePath = $this->uploadImage($image);
    
            // Update the image path in the database
            $advertisement->image = $imagePath;
        }
    
        $advertisement->update($request->except('image'));
    
        return redirect()->route('admin.advertisements.index')->with('success', 'Advertisement updated successfully');
    }
    

    private function deleteImage($imagePath)
    {
        // Delete the image file from the storage
        $fullImagePath = public_path($imagePath);
        if (file_exists($fullImagePath)) {
            unlink($fullImagePath);
        }
    }

    private function uploadImage($image)
    {
        // Generate a unique filename
        $filename = uniqid() . '_' . time() . '.' . $image->getClientOriginalExtension();

        // Define the storage path
        $storagePath = 'AdImages/';

        // Move the uploaded image to the storage path
        $image->move(public_path($storagePath), $filename);

        // Return the image path to be stored in the database
        return $storagePath . $filename;
    }

    public function AdPositionCheck(Request $request)
    {
        $page = $request->input('page');
        $position = $request->input('position');
    
        $advertisement = Advertisement::where('page', $page)
            ->where('position', $position)
            ->first();
    
        $exists = ($advertisement !== null);
    
        return response()->json([
            'exists' => $exists
        ]);
    }
    

    public function show($id)
    {
        // Retrieve the advertisement with the given ID
        // $advertisement = Advertisement::findOrFail($id);

        // // Pass the advertisement data to the view
        // return view('admin.advertisements.show', compact('advertisement'));
    }

    public function destroy(Advertisement $advertisement)
    {
        $advertisement->delete();

        return redirect()->route('admin.advertisements.index')->with('success', 'Advertisement deleted successfully');
    }

}