<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\MainNotification;
use App\Models\Notification;
use App\Models\NotificationSetting;
use App\Models\User;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\JsonResponse;
use Kreait\Firebase\Contract\Database;
use Yajra\DataTables\Facades\DataTables;

class NotificationController extends Controller
{
    public $database;
    public function __construct(Database $database)
    {
        $this->database = $database;
    }

    public function index()
    {
        $notifications = [];
        return view('admin.notifications.index', compact('notifications'));

    }

    public function getNotificationsList(Request $request){
        $sqlBuilder = MainNotification::select([
            'main_notifications.id',
            'main_notifications.title',
            'main_notifications.content',
            'main_notifications.image',
            'main_notifications.generated_by',
        ])
        ->distinct()
        ->join('notifications', 'notifications.main_notification_id', '=', 'main_notifications.id')
        ->orderBy('main_notifications.id', 'desc');

        return DataTables::of($sqlBuilder)
        ->filter(function ($query) use ($request) {
            if ($request->has('search') && !empty($request->search['value'])) {
                $query->where('main_notifications.title', 'ilike', "%" . $request->search['value'] . "%")
                    ->orWhere('main_notifications.content', 'ilike', "%" . $request->search['value'] . "%");
            }
        })
        ->editColumn('image', function ($data) {
            $icon = !empty($data->image) ? $data->image : asset('assets/images/camera_placeholder.png');
            return '<div style="text-align:center;"><img src="' . $icon . '" class="rounded-circle avatar-xs" alt="icon"></div>';
            
        })
        ->addColumn('count', function ($data) {
            $count = Notification::where('main_notification_id', $data->id)->count();
            return '<span class="badge bg-success">' . $count . '</span>';
        })
            ->addColumn('action', function ($data) {
                $html = '<div class="dropdown">
                                        <a href="#" class="btn btn-soft-secondary btn-sm" role="button" id="dropdownMenuLink5" data-bs-toggle="dropdown" aria-expanded="false">
                                            <i class="ri-more-2-fill"></i>
                                        </a>
                                        <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink5">
                                            <li><a class="dropdown-item delete-btn" data-url="' . route('admin.notifications.destroy', ['id' => $data->id]) . '">Delete</a></li>
                                        </ul>
                                    </div>';
            return $html;
            })
            ->rawColumns(['image','count','action'])
            ->make(true);
    }

    public function create(){
        $notification = "";
        $users = User::where('role_id', USER_ROLE)
        ->where('deleted',0)
        ->where('phone_verified', 1)
        ->where('status', 1)->get();

        return view('admin.notifications.submit', compact('notification','users'));

    }

    public function store(Request $request)
    {
        $rules = [
            'name' => 'required|string|max:255',
        ];
    
        $validator = Validator::make($request->all(), $rules);
    
        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'errors' => $validator->errors(),
            ], 422);
        }
    
        if ($request->id) {
            $notification = Notification::find($request->id);
    
            if (!$notification) {
                return response()->json(['status' => 'error', 'message' => 'Notification not found'], 404);
            }
    
            $notification->name = $request->name;
            if ($request->hasFile('image')) {
                $file = $request->file('image');
                    if ($file->isValid()) {
                        $storedPath = $file->store('notification_image', 'public');
                        $storedFilename = basename($storedPath);
                        $notification->image = $storedFilename;
                    }
            }
            $notification->save();
    
            return response()->json(['status' => 'success', 'message' => 'Notification updated successfully']);
        }
    }
  
    public function edit($id) {
        $notification = Notification::findOrFail($id);
        return view('admin.notifications.create', compact('notification'));
    }

    public function destroy($id): JsonResponse
    {
        try {
            $emirate = MainNotification::findOrFail($id);           
            $emirate->delete();
            return response()->json([
                'status' => 'success',
                'message' => 'Notification deleted successfully.'
            ], 200);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Notification not found.'
            ], 404);
        } catch (Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while deleting the company.'
            ], 500);
        }
    }

    public function statusChange(Request $request, $id) {
        $banner = Notification::find($id);

        if (!$banner) {
            return response()->json([
                'status' => 'error',
                'message' => 'Notification not found.'
            ], 404);
        }
    
        $banner->status = $request->status;
        $banner->save();
    
        return response()->json([
            'status' => 'success',
            'message' => 'Notification status updated successfully.'
        ]);
    }

    public function submit(Request $request)
    {
        $status     = "0";
        $message    = "";
        $o_data     = [];
        $errors     = [];
        $rules = [
            'title' => 'required',
            'title_ar'   => 'required',
            'content' => 'required',
            'content_ar' => 'required',
            'image' => 'required',
            'status' => 'required',

        ];
    
        $validator = Validator::make($request->all(),$rules);
    
        if ($validator->fails()) {
            $status = "0";
            $message = $validator->errors()->first();
            $errors = $validator->messages();
        } else {
            $imagePath = '';
            if ($request->hasFile('image')) {
                $file = $request->file('image');
                    $response = image_upload($request,config('global.notification_image_upload_dir'),'image');
                    if($response['status']){
                        $imagePath = $response['link'];
                    }
            }
        
        $mainNotification = new MainNotification();
        $mainNotification->title = $request->title;
        $mainNotification->title_ar = $request->title_ar;
        $mainNotification->content = $request->content;
        $mainNotification->content_ar = $request->content_ar;
        $mainNotification->image = $imagePath;
        $mainNotification->generated_by = auth()->user()->id;
        $mainNotification->save();
    
        foreach($request->options as $user_id){
            $noti = new Notification();
            $noti->user_id = $user_id;
            $noti->title = $request->title;
            $noti->title_ar = $request->title_ar;
            $noti->status = $request->status;
            $noti->content = $request->content;
            $noti->content_ar = $request->content_ar;
            $noti->image = $imagePath;
            $noti->status = $request->status;
            $noti->generated_by = auth()->user()->id;
            $noti->main_notification_id = $mainNotification->id;
            $noti->save();

            $order_no=$request->title;
            //$title = $request->title;
            $status = '1';

            //$description = $request->content;
            $title = $noti->title . "\n" . $noti->title_ar;
            $description = $noti->content . "\n" . $noti->content_ar;
            $notification_id = time();
            $ntype = 'public_notification';
            $user=User::find($user_id);
            $image=  $noti->image;

            send_notification_to_user(
                $this->database,
                $user,
                ['userId' => "", "imageBlur" => "0"],
                NotificationSetting::PROMOTION,
                $ntype,
                time(),
                $title,
                $description,
                $image
            );
            
        }

                $status = "1";
                $message = "Notification Sent Successfully";
    
        }
        return response()->json([
            'status' => $status,
            'errors' => $errors,
            'message' => $message,
            'oData' => $o_data
        ], 200);
    }

    public function getSearchUserList(Request $request){

            $output  = "";
            $search = $request->search;
            $datas = User::where('name', 'ilike', '%'.$search.'%')
            ->where('role_id', USER_ROLE)
            ->where('deleted',0)
            ->where('phone_verified', 1)
            ->where('status', 1)
            ->get();
    
            foreach($datas as $data){

                $output .= 
                    "<tr>
                        <td> " .
                            "<span class='custom-checkbox'>"
                                . "<input type='checkbox' id='checkbox1' class='select-customers' name='options[]' value='$data->id'> 
                            </span> 
                        </td>



                        <td> " . $data->name . "</td>
                        <td> " . $data->email . "</td>
                    </tr>";
            }
        
        return response($output);
        
    }
}
