<?php

namespace App\Http\Controllers;

use App\Models\Banners;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;

class BannerController extends Controller
{

    function deleteBanner($id)
    {
        $ban = Banners::find($id);

        $ban->delete();

        return back()->with('success', 'Banner deleted Successfully');
    }

    function updateBannerStatus($id)
    {
        $ban = Banners::find($id);

        if($ban->banner_status == 1)
        {
            $ban->banner_status = 0;
        }
        else
        {
            $ban->banner_status = 1;
        }

        $res = $ban->save();

        if ($res) {
            return back()->with('success', 'Documents status updated Successfully');
        } else {
            return back()->with('fail', 'Something went wrong');
        }
    }

    function createBanner()
    {
        return view('Admin.createBanner');
    }

    function manageAdBanner()
    {
        if(session('LoggedUser')['userRole'] == 'admin')
        {
            $data = [
                'banners' => Banners::where('created_by', '=', 'admin')->get()
            ];
        }
        else
        {
            $data = [
                'banners' => Banners::where('ClientID', '=', session('LoggedUser')['userid'])->get()
            ];
        }
        
        return view('Admin.manageBanner', $data);
    }

    function uploadBanner(Request $request)
    {
        $ClientID = session('LoggedUser')['userid'];

        if(session('LoggedUser')['userRole'] == 'admin')
        {
            $path = public_path('uploads/banners/' . $request->b_client);

            if (!File::isDirectory($path)) {
    
                File::makeDirectory($path, 0777, true, false);
            }
        }
        else
        {
            $path = public_path('uploads/banners/' . $ClientID);

            if (!File::isDirectory($path)) {
    
                File::makeDirectory($path, 0777, true, false);
            }
        }

        $file = $request->file('banner');
        $filename = time() . '.' . $file->getClientOriginalName();
        $file->move($path, $filename);

        $bann = new Banners();


        if(session('LoggedUser')['userRole'] == 'admin')
        {
            $bann->ClientID = $request->b_client;
            $bann->created_by = 'admin';
        }
        else
        {
            $bann->ClientID = $ClientID;
            $bann->created_by = $ClientID;
        }

        $bann->banner_desc = $request->b_desc;

        $bann->banner_img = $filename;

        $bann->from_date = $request->b_from;

        $bann->to_date = $request->b_to;

        $bann->banner_status = $request->b_status;

        $res = $bann->save();

        if ($res) {
            return back()->with('success', 'Banner created Successfully');
        } else {
            return back()->with('fail', 'Something went wrong');
        }
    }
}
