<?php 
require('./config/conn.php');
require('functions.php');
session_start();
// echo '<pre>';
// print_r($_POST);
// echo '</pre>';


if (isset($_POST['checkbox']['0'])) {
     
    foreach ($_POST['checkbox'] as $row) {
       $id = mysqli_real_escape_string($conn, $row);
       $query = "DELETE FROM `users` WHERE `id`='$id'";
       $query_run = mysqli_query($conn, $query);
    }
}

if (isset($_POST['deleteUser'])) {
     
  
       $id = mysqli_real_escape_string($conn, $row);
       $query = "DELETE FROM `users` WHERE `id`='$id'";
       $query_run = mysqli_query($conn, $query);
  
}

if (isset($_POST['delButton'])) {
    $id = filter($_POST['del_id']);
       $query = "DELETE FROM `users` WHERE `id`='$id'";
       $query_run = mysqli_query($conn, $query);
       if ($query_run) {
        $_SESSION['status'] = "User Deleted";
        $_SESSION['message'] = "User Deleted";
        $_SESSION['icon'] =  'success';
        header('Location: users.php');
    } else{
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Some Error Occured";
        $_SESSION['icon'] =  'error'; 
        header('Location: users.php');
    }
}

if(isset($_GET['banuser'])){

    $id = filter($_GET['banuser']);
    $query = "UPDATE `users` SET `isBanned` = '1' WHERE `id` = '$id'";
    $query_run = mysqli_query($conn, $query);

    if ($query_run) {
        $_SESSION['status'] = "User Banned";
        $_SESSION['message'] = "User Banned";
        $_SESSION['icon'] =  'success';
        header('Location: users.php');
    } else{
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Some Error Occured";

        $_SESSION['icon'] =  'error'; 
        header('Location: users.php');
    }
}

if(isset($_GET['unbanuser'])){

    $id = filter($_GET['unbanuser']);
    $query = "UPDATE `users` SET `isBanned` = '0' WHERE `id` = '$id'";
    $query_run = mysqli_query($conn, $query);

    if ($query_run) {
        $_SESSION['status'] = "User Unbanned";
        $_SESSION['message'] = "User Unbanned";
        $_SESSION['icon'] =  'success';
        header('Location: users.php');
    } else{
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Some Error Occured";
        $_SESSION['icon'] =  'error'; 
        header('Location: users.php');
    }
}

if (isset($_POST['save_user'])) {
    $id = $_POST['id'];
    $name = filter($_POST['name']);
    $email = filter($_POST['email']);
    $coins = filter($_POST['coins']);
    $totalcoins = filter($_POST['totalcoins']);

    $sql = "UPDATE `users` SET `name`='$name',`email`='$email', `coins`='$coins',`totalCoins`='$totalcoins' WHERE `id`='$id'";

    $query_run = mysqli_query($conn, $sql);

    if ($query_run) {
        $_SESSION['status'] = "Updated";
        $_SESSION['message'] = "User Updated Successfully";
        $_SESSION['icon'] =  'success';
        header('Location: users.php');
    } else{
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Some Error Occured";

        $_SESSION['icon'] =  'error'; 
        header('Location: users.php');
    }
}


if (isset($_POST['add_category'])) {
    $title = filter($_POST['title']);
    $color = filter($_POST['color']);

    $img_name = $_FILES['image']['name'];
    $img_size = $_FILES['image']['size'];
    $tmp_name = $_FILES['image']['tmp_name'];
    $error = $_FILES['image']['error'];


    if ($error === 0) {
        if ($img_size > 12000000) {
            $_SESSION['status'] = 'error';
            $_SESSION['message'] = 'Image is Large';
            header("Location: category.php");

        } else{
            $img_ex = pathinfo($img_name, PATHINFO_EXTENSION);
            $img_ex_lc = strtolower($img_ex);

            $allowed_extensions = array('png', 'jpg', 'jpeg', );

            if (in_array($img_ex_lc, $allowed_extensions)) {
               $new_image_name = uniqid("category", true).'.'. $img_ex_lc;

               $img_upload_path = "uploads/category/".$new_image_name;

               move_uploaded_file($tmp_name, $img_upload_path);

               $path = "uploads/category/". $new_image_name;

            //    Insert The Data
            $sql = "INSERT INTO `categories`(`name`, `icon`, `colorCode`) VALUES ('$title','$path','$color')";

            $query_run = mysqli_query($conn, $sql);

            if ($query_run) {
                $_SESSION['status'] = "Created";
                $_SESSION['message'] = "Category Created Successfully";
                $_SESSION['icon'] =  'success';
                header('Location: category.php');

            } else{
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Category Creating Failed ['Query Error']";
                $_SESSION['icon'] =  'error';
                header('Location: category.php');
    

            }
            } else{
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Category Adding failed [USE PNG,  JPG, JPEG Files]";
                $_SESSION['icon'] =  'error';
                header('Location: category.php');

            }
        }
    } else {
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Category Adding failed ['Some Error Occured']";
        $_SESSION['icon'] =  'error';
        header('Location: category.php');
      

    }
}

if (isset($_POST['checkbox1']['0'])) {
     
    foreach ($_POST['checkbox1'] as $row) {
       $id = mysqli_real_escape_string($conn, $row);
       $query = "DELETE FROM `categories` WHERE `id`='$id'";
       $query_run = mysqli_query($conn, $query);
    }
}


if (isset($_POST['delCatButton'])) {
    $id = filter($_POST['del_id']);
       $query = "DELETE FROM `categories` WHERE `id`='$id'";
       $query_run = mysqli_query($conn, $query);
       if ($query_run) {
        $_SESSION['status'] = "Category Deleted";
        $_SESSION['message'] = "Category Deleted";
        $_SESSION['icon'] =  'success';
        header('Location: category.php');
    } else{
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Some Error Occured";
        $_SESSION['icon'] =  'error'; 
        header('Location: category.php');
    }
}


if (isset($_POST['checking_edit_btn'])) {
    $id = $_POST['cat_id'];
    $result_array = [];
    $query = "SELECT * FROM `categories` WHERE `id`='$id'";

    $query_run = mysqli_query($conn, $query);

    if (mysqli_num_rows($query_run) > 0) {
        foreach ($query_run as $row) {
           array_push($result_array, $row); 
           header('Content-Type: application/json');
           echo json_encode($result_array);
        }
    } else {
        echo $return = "<h5>No Record Found</h5>";
    }
}


if (isset($_POST['edit_category'])) {
    $id = filter($_POST['id']);
    $oldIcon = filter($_POST['oldImage']);
    $name = filter($_POST['category_name']);
    $color = filter($_POST['color']);

   

    $img_name = $_FILES['category_image']['name'];
    $img_size = $_FILES['category_image']['size'];
    $tmp_name = $_FILES['category_image']['tmp_name'];
    $error = $_FILES['category_image']['error'];


   

    if ($_FILES['category_image']['name'] == "") {
        $icon = $oldIcon;
    } else{
        if ($error === 0) {
            if ($img_size > 12000000) {
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Error ocurred!";
                $_SESSION['icon'] =  'error';
                header('Location: category.php');
    
            } else{
                $img_ex = pathinfo($img_name, PATHINFO_EXTENSION);
                $img_ex_lc = strtolower($img_ex);
    
                $allowed_extensions = array('png', 'jpg', 'jpeg');
    
                if (in_array($img_ex_lc, $allowed_extensions)) {
                   $new_image_name = uniqid("category", true).'.'. $img_ex_lc;
    
                   $img_upload_path = "uploads/category/".$new_image_name;
    
                   move_uploaded_file($tmp_name, $img_upload_path);
    
                   $path = "uploads/category/". $new_image_name;
                   $icon = $path;
                   unlink($_POST['oldImage']);
    
                } else{
                    $_SESSION['status'] = "Error";
                    $_SESSION['message'] = "Error ocurred! [Use PNG, JPG, JPEG]";
                    $_SESSION['icon'] =  'error';
                    header('Location: category.php');
    
                }
            }
    }
  }

  $sql = "UPDATE `categories` SET `name`='$name',`icon`='$icon',`colorCode`='$color'  WHERE `id`='$id'";

  $query_run = mysqli_query($conn, $sql);

  if ($query_run) {
    $_SESSION['status'] = "Edited";
    $_SESSION['message'] = "Category Edited Successfully";
    $_SESSION['icon'] =  'success';
    header('Location: category.php');
  } else{
    $_SESSION['status'] = "Error";
                    $_SESSION['message'] = "Error ocurred!";
                    $_SESSION['icon'] =  'error';
                    header('Location: category.php');
  }
}


if (isset($_GET['pincat'])) {
    $id = $_GET['pincat'];

    $sql = "UPDATE `categories` SET `priority` = '1' WHERE `categories`.`id` = '$id'";
    $query_run = mysqli_query($conn, $sql);

  if ($query_run) {
    $_SESSION['status'] = "Pinned";
    $_SESSION['message'] = "Category Pinned";
    $_SESSION['icon'] =  'success';
    header('Location: category.php');
  } else{
      $_SESSION['status'] = "Error";
      $_SESSION['message'] = "Error ocurred!";
      $_SESSION['icon'] =  'error';
      header('Location: category.php');
  }
}

if (isset($_GET['unpin'])) {
    $id = $_GET['unpin'];

    $sql = "UPDATE `categories` SET `priority` = '0' WHERE `categories`.`id` = '$id'";
    $query_run = mysqli_query($conn, $sql);

  if ($query_run) {
    $_SESSION['status'] = "Unpinned";
    $_SESSION['message'] = "Category Unpinned";
    $_SESSION['icon'] =  'success';
    header('Location: category.php');
  } else{
      $_SESSION['status'] = "Error";
      $_SESSION['message'] = "Error ocurred!";
      $_SESSION['icon'] =  'error';
      header('Location: category.php');
  }
}







if (isset($_POST['add_quiz'])) {
    $title = filter($_POST['title']);
    $color = filter($_POST['color']);

    $img_name = $_FILES['image']['name'];
    $img_size = $_FILES['image']['size'];
    $tmp_name = $_FILES['image']['tmp_name'];
    $error = $_FILES['image']['error'];

    $category_id = filter($_POST['category_id']);
    $category_name = filter($_POST['category_name']);
    $entryFee = filter($_POST['entryFee']);
    $questionsLimit = filter($_POST['questionsLimit']);
    $ppp = filter($_POST['ppp']);
    $livesAvailable = filter($_POST['livesAvailable']);
    $time = filter($_POST['time']);




    if (isset($_POST['easy'])) {
        $easy = 1;
    } else{
       $easy = 0;
    }
    if (isset($_POST['medium'])) {
       $medium = 1;
    } else{
        $medium = 0;
    }
    if (isset($_POST['hard'])) {
       $hard = 1;
    } else{
        $hard = 0;
    }




    if ($error === 0) {
        if ($img_size > 12000000) {
            $_SESSION['status'] = 'error';
            $_SESSION['message'] = 'Image is Large';
            header("Location: quiz.php");

        } else{
            $img_ex = pathinfo($img_name, PATHINFO_EXTENSION);
            $img_ex_lc = strtolower($img_ex);

            $allowed_extensions = array('png', 'jpg', 'jpeg', );

            if (in_array($img_ex_lc, $allowed_extensions)) {
               $new_image_name = uniqid("quizzes", true).'.'. $img_ex_lc;

               $img_upload_path = "uploads/quizzes/".$new_image_name;

               move_uploaded_file($tmp_name, $img_upload_path);

               $path = "uploads/quizzes/". $new_image_name;

            //    Insert The Data
            $sql = "INSERT INTO `quizzes`(`categoryId`, `name`, `icon`, `entryFee`, `prizePerQuestion`, `colorCode`, `questionLimit`, `livesAvailable`, `easy`, `medium`, `hard`, `time`) VALUES ('$category_id','$title','$path','$entryFee','$ppp','$color','$questionsLimit','$livesAvailable','$easy','$medium','$hard','$time')";

            $sql2 = "UPDATE `categories` SET `totalQuizzes` = `totalQuizzes`+1 WHERE `name` = '$category_name'";
            $query_run = mysqli_query($conn, $sql);
            $query_run2 = mysqli_query($conn, $sql2);

            if ($query_run && $query_run2) {
                $_SESSION['status'] = "Created";
                $_SESSION['message'] = "Quiz Created Successfully";
                $_SESSION['icon'] =  'success';
                header('Location: quiz.php');

            } else{
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Quiz Creating Failed ['Query Error']";
                $_SESSION['icon'] =  'error';
                header('Location: quiz.php');
    

            }
            } else{
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Quiz Adding failed [USE PNG,  JPG, JPEG Files]";
                $_SESSION['icon'] =  'error';
                header('Location: quiz.php');

            }
        }
    } else {
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Quiz Adding failed ['Some Error Occured']";
        $_SESSION['icon'] =  'error';
        header('Location: quiz.php');
      

    }
}




if (isset($_POST['checkbox2']['0'])) {
     
    foreach ($_POST['checkbox2'] as $row) {
       $id = mysqli_real_escape_string($conn, $row);
       $query = "DELETE FROM `quizzes` WHERE `id`='$id'";
       $query_run = mysqli_query($conn, $query);
    }
}



if (isset($_POST['delQuizButton'])) {
    $id = filter($_POST['del_id']);
       $query = "DELETE FROM `quizzes` WHERE `id`='$id'";
       $query_run = mysqli_query($conn, $query);
       if ($query_run) {
        $_SESSION['status'] = "Quiz Deleted";
        $_SESSION['message'] = "Quiz Deleted";
        $_SESSION['icon'] =  'success';
        header('Location: quiz.php');
    } else{
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Some Error Occured";
        $_SESSION['icon'] =  'error'; 
        header('Location: quiz.php');
    }
}



if (isset($_GET['pinquiz'])) {
    $id = $_GET['pinquiz'];

    $sql = "UPDATE `quizzes` SET `priority` = '1' WHERE `quizzes`.`id` = '$id'";
    $query_run = mysqli_query($conn, $sql);

  if ($query_run) {
    $_SESSION['status'] = "Pinned";
    $_SESSION['message'] = "Quiz Pinned";
    $_SESSION['icon'] =  'success';
    header('Location: quiz.php');
  } else{
      $_SESSION['status'] = "Error";
      $_SESSION['message'] = "Error ocurred!";
      $_SESSION['icon'] =  'error';
      header('Location: quiz.php');
  }
}

if (isset($_GET['unpinquiz'])) {
    $id = $_GET['unpinquiz'];

    $sql = "UPDATE `quizzes` SET `priority` = '0' WHERE `quizzes`.`id` = '$id'";
    $query_run = mysqli_query($conn, $sql);

  if ($query_run) {
    $_SESSION['status'] = "Unpinned";
    $_SESSION['message'] = "Quiz Unpinned";
    $_SESSION['icon'] =  'success';
    header('Location: quiz.php');
  } else{
      $_SESSION['status'] = "Error";
      $_SESSION['message'] = "Error ocurred!";
      $_SESSION['icon'] =  'error';
      header('Location: quiz.php');
  }
}


if (isset($_POST['checking_edit_quiz_btn'])) {
    $id = $_POST['quiz_id'];
    $result_array = [];
    $query = "SELECT * FROM `quizzes` WHERE `id`='$id'";

    $query_run = mysqli_query($conn, $query);

    if (mysqli_num_rows($query_run) > 0) {
        foreach ($query_run as $row) {
           array_push($result_array, $row); 

           header('Content-Type: application/json');
           echo json_encode($result_array);
        }
    } else {
        echo $return = "<h5>No Record Found</h5>";
    }
}

if (isset($_POST['get_category'])) {
    $id = filter($_POST['cat_id']);
    $result_array = [];
    $query = "SELECT * FROM `categories` WHERE `id`=$id";


    $query_run = mysqli_query($conn, $query);

    if (mysqli_num_rows($query_run) > 0) {
        foreach ($query_run as $row) {
            array_push($result_array, $row); 

           header('Content-Type: application/json');
           echo json_encode($result_array);
        }
    } else {
        echo $return = "<h5>No Record Found</h5>";
    }

}





if (isset($_POST['edit_quiz'])) {
    $id = filter($_POST['id']);
    $oldIcon = filter($_POST['oldImage']);
    $name = filter($_POST['quiz_name']);
    $color = filter($_POST['color']);

   

    $img_name = $_FILES['quiz_image']['name'];
    $img_size = $_FILES['quiz_image']['size'];
    $tmp_name = $_FILES['quiz_image']['tmp_name'];
    $error = $_FILES['quiz_image']['error'];


    $category_id = filter($_POST['category_id']);
    $entryFee = filter($_POST['entryFee']);
    $questionsLimit = filter($_POST['questionsLimit']);
    $ppp = filter($_POST['ppp']);
    $livesAvailable = filter($_POST['livesAvailable']);
    $time = filter($_POST['time']);




    if (isset($_POST['easy'])) {
        $easy = 1;
    } else{
       $easy = 0;
    }
    if (isset($_POST['medium'])) {
       $medium = 1;
    } else{
        $medium = 0;
    }
    if (isset($_POST['hard'])) {
       $hard = 1;
    } else{
        $hard = 0;
    }

   

    if ($_FILES['quiz_image']['name'] == "") {
        $icon = $oldIcon;
    } else{
        if ($error === 0) {
            if ($img_size > 12000000) {
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Error ocurred!";
                $_SESSION['icon'] =  'error';
                header('Location: quiz.php');
    
            } else{
                $img_ex = pathinfo($img_name, PATHINFO_EXTENSION);
                $img_ex_lc = strtolower($img_ex);
    
                $allowed_extensions = array('png', 'jpg', 'jpeg');
    
                if (in_array($img_ex_lc, $allowed_extensions)) {
                   $new_image_name = uniqid("quizzes", true).'.'. $img_ex_lc;
    
                   $img_upload_path = "uploads/quizzes/".$new_image_name;
    
                   move_uploaded_file($tmp_name, $img_upload_path);
    
                   $path = "uploads/quizzes/". $new_image_name;
                   $icon = $path;
                   unlink($_POST['oldImage']);
    
                } else{
                    $_SESSION['status'] = "Error";
                    $_SESSION['message'] = "Error ocurred! [Use PNG, JPG, JPEG]";
                    $_SESSION['icon'] =  'error';
                    header('Location: quiz.php');
    
                }
            }
    }
  }

  $sql = "UPDATE `quizzes` SET `categoryId`='$category_id',`name`='$name',`icon`='$icon',`entryFee`='$entryFee',`prizePerQuestion`='$ppp',`colorCode`='$color',`questionLimit`='$questionsLimit',`livesAvailable`='$livesAvailable',`easy`='$easy',`medium`='$medium',`hard`='$hard',`time`='$time' WHERE `id`='$id'";

  $query_run = mysqli_query($conn, $sql);

  if ($query_run) {
    $_SESSION['status'] = "Edited";
    $_SESSION['message'] = "Quiz Edited Successfully";
    $_SESSION['icon'] =  'success';
    header('Location: quiz.php');
  } else{
    $_SESSION['status'] = "Error";
                    $_SESSION['message'] = "Error ocurred!";
                    $_SESSION['icon'] =  'error';
                    header('Location: quiz.php');
  }
}

if (isset($_POST['add_ind_question'])) {

    $question = filter($_POST['question']);
    $optionA = filter($_POST['optionA']);
    $optionB = filter($_POST['optionB']);
    $optionC = filter($_POST['optionC']);
    $optionD = filter($_POST['optionD']);
    $answer = filter($_POST['answer']);
    $quiz = filter($_POST['quiz_id']);
    $difficulty = filter($_POST['difficulty']);
    $img_name = $_FILES['image']['name'];
    $img_size = $_FILES['image']['size'];
    $tmp_name = $_FILES['image']['tmp_name'];
    $error = $_FILES['image']['error'];

    switch ($answer) {
        case 'a':
            $answer = $optionA;
            break;
        case 'b':
            $answer = $optionB;
            break;
        case 'c':
            $answer = $optionC;
            break;
        case 'd':
            $answer = $optionD;
            break;
        
        default:
            $answer = 'answer';
            break;
    }


    if ($error === 0) {
        if ($img_size > 12000000) {
            $_SESSION['status'] = 'error';
            $_SESSION['message'] = 'Image is Large';
            header("Location: questions.php");

        } else{
            $img_ex = pathinfo($img_name, PATHINFO_EXTENSION);
            $img_ex_lc = strtolower($img_ex);

            $allowed_extensions = array('png', 'jpg', 'jpeg');

            if (in_array($img_ex_lc, $allowed_extensions)) {
               $new_image_name = uniqid("question", true).'.'. $img_ex_lc;

               $img_upload_path = "uploads/questions/".$new_image_name;

               move_uploaded_file($tmp_name, $img_upload_path);

               $path = "uploads/questions/". $new_image_name;

          
            } else{
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Quiz Adding failed [USE PNG,  JPG, JPEG Files]";
                $_SESSION['icon'] =  'error';
                header('Location: questions.php');

            }
        }



         
    } else {
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Quiz Adding failed ['Some Error Occured']";
        $_SESSION['icon'] =  'error';
        header('Location: questions.php');
      
    }


    global $path;
     //    Insert The Data
     $sql = "INSERT INTO `questions`(`question`, `image`, `optionA`, `optionB`, `optionC`, `optionD`, `answer`, `quizId`, `difficulty`) VALUES ('$question','$path','$optionA','$optionB','$optionC','$optionD','$answer','$quiz','$difficulty')";

     $query_run = mysqli_query($conn, $sql);

     if ($query_run) {
         $_SESSION['status'] = "Added";
         $_SESSION['message'] = "Question Added Successfully";
         $_SESSION['icon'] =  'success';
         header('Location: questions.php');

     } else{
         $_SESSION['status'] = "Error";
         $_SESSION['message'] = "Question Adding Failed ['Query Error']";
         $_SESSION['icon'] =  'error';
         header('Location: questions.php');


     }
}


if (isset($_POST['checkbox3']['0'])) {
     
    foreach ($_POST['checkbox3'] as $row) {
       $id = mysqli_real_escape_string($conn, $row);
       $query = "DELETE FROM `questions` WHERE `id`='$id'";
       $query_run = mysqli_query($conn, $query);
    }
}



if (isset($_POST['delQuesBtn'])) {
    $id = filter($_POST['del_id']);
       $query = "DELETE FROM `questions` WHERE `id`='$id'";
       $query_run = mysqli_query($conn, $query);
       if ($query_run) {
        $_SESSION['status'] = "Question Deleted";
        $_SESSION['message'] = "Question Deleted";
        $_SESSION['icon'] =  'success';
        header('Location: questions.php');
    } else{
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Some Error Occured";
        $_SESSION['icon'] =  'error'; 
        header('Location: questions.php');
    }
}


if (isset($_POST['checkbox4']['0'])) {
     
    foreach ($_POST['checkbox4'] as $row) {
       $id = mysqli_real_escape_string($conn, $row);
       $query = "DELETE FROM `dailyquizquestions` WHERE `id`='$id'";
       $query_run = mysqli_query($conn, $query);
    }
}






if (isset($_POST['checking_edit_ques_btn'])) {
    $id = $_POST['ques_id'];
    $result_array = [];
    $query = "SELECT * FROM `questions` WHERE `id`='$id'";

    $query_run = mysqli_query($conn, $query);

    if (mysqli_num_rows($query_run) > 0) {
        foreach ($query_run as $row) {
           array_push($result_array, $row); 

           header('Content-Type: application/json');
           echo json_encode($result_array);
        }
    } else {
        echo $return = "<h5>No Record Found</h5>";
    }
}

if (isset($_POST['get_quiz'])) {
    $id = filter($_POST['quiz_id']);
    $result_array = [];
    $query = "SELECT * FROM `quizzes` WHERE `id`=$id";


    $query_run = mysqli_query($conn, $query);

    if (mysqli_num_rows($query_run) > 0) {
        foreach ($query_run as $row) {
            array_push($result_array, $row); 

           header('Content-Type: application/json');
           echo json_encode($result_array);
        }
    } else {
        echo $return = "<h5>No Record Found</h5>";
    }

}


if (isset($_POST['edit_question'])) {
    $id = filter($_POST['id']);
    $question = filter($_POST['question']);
    $optionA = filter($_POST['optionA']);
    $optionB = filter($_POST['optionB']);
    $optionC = filter($_POST['optionC']);
    $optionD = filter($_POST['optionD']);
    $answer = filter($_POST['answer']);
    $quiz = filter($_POST['quiz_id']);
    $difficulty = filter($_POST['difficulty']);

   

    $img_name = $_FILES['image']['name'];
    $img_size = $_FILES['image']['size'];
    $tmp_name = $_FILES['image']['tmp_name'];
    $error = $_FILES['image']['error'];
    $oldIcon = $_POST['oldImage'];
    switch ($answer) {
        case 'a':
            $answer = $optionA;
            break;
        case 'b':
            $answer = $optionB;
            break;
        case 'c':
            $answer = $optionC;
            break;
        case 'd':
            $answer = $optionD;
            break;
        
        default:
            $answer = 'answer';
            break;
    }



   

    if ($_FILES['image']['name'] == "") {
        $icon = $oldIcon;
    } else{
        if ($error === 0) {
            if ($img_size > 12000000) {
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Error ocurred!";
                $_SESSION['icon'] =  'error';
                header('Location: quiz.php');
    
            } else{
                $img_ex = pathinfo($img_name, PATHINFO_EXTENSION);
                $img_ex_lc = strtolower($img_ex);
    
                $allowed_extensions = array('png', 'jpg', 'jpeg');
    
                if (in_array($img_ex_lc, $allowed_extensions)) {
                   $new_image_name = uniqid("question", true).'.'. $img_ex_lc;
    
                   $img_upload_path = "uploads/questions/".$new_image_name;
    
                   move_uploaded_file($tmp_name, $img_upload_path);
    
                   $path = "uploads/questions/". $new_image_name;
                   $icon = $path;
                   unlink($_POST['oldImage']);
    
                } else{
                    $_SESSION['status'] = "Error";
                    $_SESSION['message'] = "Error ocurred! [Use PNG, JPG, JPEG]";
                    $_SESSION['icon'] =  'error';
                    header('Location: questions.php');
    
                }
            }
    }
  }

  $sql = "UPDATE `questions` SET `question`='$question',`image`='$icon',`optionA`='$optionA',`optionB`='$optionB',`optionC`='$optionC',`optionD`='$optionD',`answer`='$answer',`quizId`='$quiz',`difficulty`='$difficulty' WHERE `id`='$id'";

  $query_run = mysqli_query($conn, $sql);

  if ($query_run) {
    $_SESSION['status'] = "Edited";
    $_SESSION['message'] = "Question Edited Successfully";
    $_SESSION['icon'] =  'success';
    header('Location: questions.php');
  } else{
      $_SESSION['status'] = "Error";
      $_SESSION['icon'] =  'error';
      $_SESSION['message'] = "Error ocurred!";
      header('Location: questions.php');
  }
}


if (isset($_POST['checkbox4']['0'])) {
     
    foreach ($_POST['checkbox4'] as $row) {
       $id = mysqli_real_escape_string($conn, $row);
       $query = "DELETE FROM `dailyquizquestions` WHERE `id`='$id'";
       $query_run = mysqli_query($conn, $query);
    }
}



if (isset($_POST['add_daily_ind_question'])) {

    $question = filter($_POST['question']);
    $optionA = filter($_POST['optionA']);
    $optionB = filter($_POST['optionB']);
    $optionC = filter($_POST['optionC']);
    $optionD = filter($_POST['optionD']);
    $answer = filter($_POST['answer']);
    $img_name = $_FILES['image']['name'];
    $img_size = $_FILES['image']['size'];
    $tmp_name = $_FILES['image']['tmp_name'];
    $error = $_FILES['image']['error'];

    switch ($answer) {
        case 'a':
            $answer = $optionA;
            break;
        case 'b':
            $answer = $optionB;
            break;
        case 'c':
            $answer = $optionC;
            break;
        case 'd':
            $answer = $optionD;
            break;
        
        default:
            $answer = 'answer';
            break;
    }


    if ($error === 0) {
        if ($img_size > 12000000) {
            $_SESSION['status'] = 'error';
            $_SESSION['message'] = 'Image is Large';
            header("Location: dailyquiz.php");

        } else{
            $img_ex = pathinfo($img_name, PATHINFO_EXTENSION);
            $img_ex_lc = strtolower($img_ex);

            $allowed_extensions = array('png', 'jpg', 'jpeg');

            if (in_array($img_ex_lc, $allowed_extensions)) {
               $new_image_name = uniqid("daily-question", true).'.'. $img_ex_lc;

               $img_upload_path = "uploads/daily-questions/".$new_image_name;

               move_uploaded_file($tmp_name, $img_upload_path);

               $path = "uploads/daily-questions/". $new_image_name;

          
            } else{
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Quiz Adding failed [USE PNG,  JPG, JPEG Files]";
                $_SESSION['icon'] =  'error';
                header('Location: dailyquiz.php');

            }
        }



         
    } else {
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Quiz Adding failed ['Some Error Occured']";
        $_SESSION['icon'] =  'error';
        header('Location: dailyquiz.php');
      
    }


    global $path;
     //    Insert The Data
     $sql = "INSERT INTO `dailyquizquestions` (`question`, `image`, `optionA`, `optionB`, `optionC`, `optionD`, `answer`, `questionDate`) VALUES ('$question', '$image', '$optionA', '$optionB', '$optionC', '$optionD', '$answer', current_timestamp());";
     $query_run = mysqli_query($conn, $sql);

     if ($query_run) {
         $_SESSION['status'] = "Added";
         $_SESSION['message'] = "Question Added Successfully";
         $_SESSION['icon'] =  'success';
         header('Location: dailyquiz.php');

     } else{
         $_SESSION['status'] = "Error";
         $_SESSION['message'] = "Question Adding Failed ['Query Error']";
         $_SESSION['icon'] =  'error';
         header('Location: dailyquiz.php');


     }
}



if (isset($_POST['delDaiQuesBtn'])) {
    $id = filter($_POST['del_id']);
       $query = "DELETE FROM `dailyquizquestions` WHERE `id`='$id'";
       $query_run = mysqli_query($conn, $query);
       if ($query_run) {
        $_SESSION['status'] = "Question Deleted";
        $_SESSION['message'] = "Question Deleted";
        $_SESSION['icon'] =  'success';
        header('Location: dailyquiz.php');
    } else{
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Some Error Occured";
        $_SESSION['icon'] =  'error'; 
        header('Location: dailyquiz.php');
    }
}

if (isset($_POST['edit_daily_quiz_settings'])) {
    $entryFee = filter($_POST['entryFee']);
    $ppp = filter($_POST['ppp']);
    $questionsLimit = filter($_POST['questionsLimit']);
    $linesAvailable = filter($_POST['linesAvailable']);
    $quizTime = filter($_POST['quizTime']);
    

    $sql1 = "UPDATE `dailyquizsettings` SET `value`='$entryFee' WHERE `name`='Entry Fee'";
    $sql2 = "UPDATE `dailyquizsettings` SET `value`='$ppp' WHERE `name`='Prize Per Question'";
    $sql3 = "UPDATE `dailyquizsettings` SET `value`='$questionsLimit' WHERE `name`='Question Limit'";
    $sql4 = "UPDATE `dailyquizsettings` SET `value`='$linesAvailable' WHERE `name`='Lives Available'";
    $sql5 = "UPDATE `dailyquizsettings` SET `value`='$quizTime' WHERE `name`='Quiz Time'";

    $query_run1 = mysqli_query($conn, $sql1);
    $query_run2 = mysqli_query($conn, $sql2);
    $query_run3 = mysqli_query($conn, $sql3);
    $query_run4 = mysqli_query($conn, $sql4);
    $query_run5 = mysqli_query($conn, $sql5);
    if ($query_run1 && $query_run2 && $query_run3 && $query_run4 && $query_run5) {
        $_SESSION['status'] = "Updated";
        $_SESSION['message'] = "Settings Updated";
        $_SESSION['icon'] =  'success';
        header('Location: dailyquiz.php');
    } else{
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Some Error Occured";
        $_SESSION['icon'] =  'error'; 
        header('Location: dailyquiz.php');
    }

}



if (isset($_POST['checking_edit_dai_ques_btn'])) {
    $id = $_POST['ques_dai_id'];
    $result_array = [];
    $query = "SELECT * FROM `dailyquizquestions` WHERE `id`='$id'";

    $query_run = mysqli_query($conn, $query);

    if (mysqli_num_rows($query_run) > 0) {
        foreach ($query_run as $row) {
           array_push($result_array, $row); 

           header('Content-Type: application/json');
           echo json_encode($result_array);
        }
    } else {
        echo $return = "<h5>No Record Found</h5>";
    }
}





if (isset($_POST['edit_dai_question'])) {
    $id = filter($_POST['id']);
    $question = filter($_POST['question']);
    $optionA = filter($_POST['optionA']);
    $optionB = filter($_POST['optionB']);
    $optionC = filter($_POST['optionC']);
    $optionD = filter($_POST['optionD']);
    $answer = filter($_POST['answer']);

   

    $img_name = $_FILES['image']['name'];
    $img_size = $_FILES['image']['size'];
    $tmp_name = $_FILES['image']['tmp_name'];
    $error = $_FILES['image']['error'];
    $oldIcon = $_POST['oldImage'];

    switch ($answer) {
        case 'a':
            $answer = $optionA;
            break;
        case 'b':
            $answer = $optionB;
            break;
        case 'c':
            $answer = $optionC;
            break;
        case 'd':
            $answer = $optionD;
            break;
        
        default:
            $answer = 'answer';
            break;
    }


   

    if ($_FILES['image']['name'] == "") {
        $icon = $oldIcon;
    } else{
        if ($error === 0) {
            if ($img_size > 12000000) {
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Error ocurred!";
                $_SESSION['icon'] =  'error';
                header('Location: quiz.php');
    
            } else{
                $img_ex = pathinfo($img_name, PATHINFO_EXTENSION);
                $img_ex_lc = strtolower($img_ex);
    
                $allowed_extensions = array('png', 'jpg', 'jpeg');
    
                if (in_array($img_ex_lc, $allowed_extensions)) {
                   $new_image_name = uniqid("daily-question", true).'.'. $img_ex_lc;
    
                   $img_upload_path = "uploads/daily-questions/".$new_image_name;
    
                   move_uploaded_file($tmp_name, $img_upload_path);
    
                   $path = "uploads/daily-questions/". $new_image_name;
                   $icon = $path;
                   unlink($_POST['oldImage']);
    
                } else{
                    $_SESSION['status'] = "Error";
                    $_SESSION['message'] = "Error ocurred! [Use PNG, JPG, JPEG]";
                    $_SESSION['icon'] =  'error';
                    header('Location: questions.php');
    
                }
            }
    }
  }

  $sql = "UPDATE `dailyquizquestions` SET `question`='$question',`image`='$icon',`optionA`='$optionA',`optionB`='$optionB',`optionC`='$optionC',`optionD`='$optionD',`answer`='$answer' WHERE `id`='$id'";

  $query_run = mysqli_query($conn, $sql);

  if ($query_run) {
    $_SESSION['status'] = "Edited";
    $_SESSION['message'] = "Question Edited Successfully";
    $_SESSION['icon'] =  'success';
    header('Location: dailyquiz.php');
  } else{
      $_SESSION['status'] = "Error";
      $_SESSION['icon'] =  'error';
      $_SESSION['message'] = "Error ocurred!";
      header('Location: dailyquiz.php');
  }
}


if (isset($_POST['add_game'])) {
   $title = filter($_POST['title']);
   $url = filter($_POST['gameurl']);
   $color = filter($_POST['color']);


   $img_name = $_FILES['image']['name'];
    $img_size = $_FILES['image']['size'];
    $tmp_name = $_FILES['image']['tmp_name'];
    $error = $_FILES['image']['error'];

   $img_name2 = $_FILES['bcimage']['name'];
    $img_size2 = $_FILES['bcimage']['size'];
    $tmp_name2 = $_FILES['bcimage']['tmp_name'];
    $error2 = $_FILES['bcimage']['error'];


    if ($error === 0 && $error2 === 0) {
        if ($img_size > 12000000 && $img_size2 > 12000000) {
            $_SESSION['status'] = 'error';
            $_SESSION['message'] = 'Image is Large';
            header("Location: games.php");

        } else{
            $img_ex = pathinfo($img_name, PATHINFO_EXTENSION);
            $img_ex_lc = strtolower($img_ex);
            $img_ex2 = pathinfo($img_name2, PATHINFO_EXTENSION);
            $img_ex_lc2 = strtolower($img_ex2);

            $allowed_extensions = array('png', 'jpg', 'jpeg', );

            if (in_array($img_ex_lc, $allowed_extensions) && in_array($img_ex_lc2, $allowed_extensions) ) {
               $new_image_name = uniqid("game", true).'.'. $img_ex_lc;
               $new_image_name2 = uniqid("game", true).'.'. $img_ex_lc2;

               $img_upload_path = "uploads/games/".$new_image_name;
               $img_upload_path2 = "uploads/games/".$new_image_name2;

               move_uploaded_file($tmp_name, $img_upload_path);
                move_uploaded_file($tmp_name2, $img_upload_path2);

               $path = "uploads/games/". $new_image_name;
               $path2 = "uploads/games/". $new_image_name2;

            //    Insert The Data
            $sql = "INSERT INTO `games` (`name`, `icon`, `gameUrl`, `colorCode`, `bgImage`) VALUES ('$title', '$path', '$url', '$color', '$path2');";

            $query_run = mysqli_query($conn, $sql);

            if ($query_run) {
                $_SESSION['status'] = "Added";
                $_SESSION['message'] = "Game Added Successfully";
                $_SESSION['icon'] =  'success';
                header('Location: games.php');

            } else{
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Game Adding Failed ['Query Error']";
                $_SESSION['icon'] =  'error';
                header('Location: games.php');
    

            }
            } else{
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Game Adding failed [USE PNG,  JPG, JPEG Files]";
                $_SESSION['icon'] =  'error';
                header('Location: games.php');

            }
        }
    } else {
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Game Adding failed ['Some Error Occured']";
        $_SESSION['icon'] =  'error';
        header('Location: games.php');
      

    }
}


if (isset($_POST['checkbox5']['0'])) {
     
    foreach ($_POST['checkbox5'] as $row) {
       $id = mysqli_real_escape_string($conn, $row);
       $query = "DELETE FROM `games` WHERE `id`='$id'";
       $query_run = mysqli_query($conn, $query);
    }
}



if (isset($_POST['delGames'])) {
    $id = filter($_POST['del_id']);
       $query = "DELETE FROM `games` WHERE `id`='$id'";
       $query_run = mysqli_query($conn, $query);
       if ($query_run) {
        $_SESSION['status'] = "Game Deleted";
        $_SESSION['message'] = "Game Deleted";
        $_SESSION['icon'] =  'success';
        header('Location: games.php');
    } else{
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Some Error Occured";
        $_SESSION['icon'] =  'error'; 
        header('Location: games.php');
    }
}

if (isset($_POST['checking_edit_games_btn'])) {
    $id = $_POST['game_id'];
    $result_array = [];
    $query = "SELECT * FROM `games` WHERE `id`='$id'";

    $query_run = mysqli_query($conn, $query);

    if (mysqli_num_rows($query_run) > 0) {
        foreach ($query_run as $row) {
           array_push($result_array, $row); 

           header('Content-Type: application/json');
           echo json_encode($result_array);
        }
    } else {
        echo $return = "<h5>No Record Found</h5>";
    }
}





if (isset($_POST['edit_game'])) {

    $id = filter($_POST['id']);
    $name = filter($_POST['game_name']);
    $url = filter($_POST['url']);
    $color = filter($_POST['color']);
    $oldIcon = filter($_POST['oldImage']);
    $oldBgImage = filter($_POST['old-bg-image']);



    $img_name = $_FILES['game_image']['name'];
    $img_size = $_FILES['game_image']['size'];
    $tmp_name = $_FILES['game_image']['tmp_name'];
    $error = $_FILES['game_image']['error'];

    $img_name_bg  = $_FILES['bg_image']['name'];
    $img_size_bg  = $_FILES['bg_image']['size'];
    $tmp_name_bg  = $_FILES['bg_image']['tmp_name'];
    $error_bg  = $_FILES['bg_image']['error'];

    if ($_FILES['game_image']['name'] == "") {
        $icon = $oldIcon;
    } else{
        if ($error === 0) {
            if ($img_size > 12000000) {
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Error ocurred!";
                $_SESSION['icon'] =  'error';
                header('Location: games.php');
    
            } else{
                $img_ex = pathinfo($img_name, PATHINFO_EXTENSION);
                $img_ex_lc = strtolower($img_ex);
    
                $allowed_extensions = array('png', 'jpg', 'jpeg');
    
                if (in_array($img_ex_lc, $allowed_extensions)) {
                   $new_image_name = uniqid("game", true).'.'. $img_ex_lc;
    
                   $img_upload_path = "uploads/games/".$new_image_name;
    
                   move_uploaded_file($tmp_name, $img_upload_path);
    
                   $path = "uploads/games/". $new_image_name;
                   $icon = $path;
                   unlink($_POST['oldImage']);
    
                } else{
                    $_SESSION['status'] = "Error";
                    $_SESSION['message'] = "Error ocurred! [Use PNG, JPG, JPEG]";
                    $_SESSION['icon'] =  'error';
                    header('Location: games.php');
    
                }
            }
    }
  }
    if ($_FILES['bg_image']['name'] == "") {
        $icon_bg = $oldBgImage;
    } else{
        if ($error_bg === 0) {
            if ($img_size > 12000000) {
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Error ocurred!";
                $_SESSION['icon'] =  'error';
                header('Location: games.php');
    
            } else{
                $img_ex = pathinfo($img_name_bg, PATHINFO_EXTENSION);
                $img_ex_lc = strtolower($img_ex);
    
                $allowed_extensions = array('png', 'jpg', 'jpeg');
    
                if (in_array($img_ex_lc, $allowed_extensions)) {
                   $new_image_name = uniqid("game", true).'.'. $img_ex_lc;
    
                   $img_upload_path = "uploads/games/".$new_image_name;
    
                   move_uploaded_file($tmp_name_bg, $img_upload_path);
    
                   $path = "uploads/games/". $new_image_name;
                   $icon_bg = $path;
                   unlink($_POST['old-bg-image']);
    
                } else{
                    $_SESSION['status'] = "Error";
                    $_SESSION['message'] = "Error ocurred! [Use PNG, JPG, JPEG]";
                    $_SESSION['icon'] =  'error';
                    header('Location: games.php');
    
                }
            }
    }
  }


  $sql = "UPDATE `games` SET `name`='$name',`icon`='$icon',`gameUrl`='$url',`colorCode`='$color',`bgImage`='$icon_bg' WHERE `id`='$id'";

  $query_run = mysqli_query($conn, $sql);

  if ($query_run) {
        $_SESSION['status'] = "Game Edited";
        $_SESSION['message'] = "Game Edited Successfully";
        $_SESSION['icon'] =  'success';
        header('Location: games.php');
    } else{
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Some Error Occured";
        $_SESSION['icon'] =  'error'; 
        header('Location: games.php');
    }
}





if (isset($_GET['pingame'])) {
    $id = $_GET['pingame'];

    $sql = "UPDATE `games` SET `priority` = '1' WHERE `games`.`id` = '$id'";
    $query_run = mysqli_query($conn, $sql);

  if ($query_run) {
    $_SESSION['status'] = "Pinned";
    $_SESSION['message'] = "Game Pinned";
    $_SESSION['icon'] =  'success';
    header('Location: games.php');
  } else{
      $_SESSION['status'] = "Error";
      $_SESSION['message'] = "Error ocurred!";
      $_SESSION['icon'] =  'error';
      header('Location: games.php');
  }
}

if (isset($_GET['unpingame'])) {
    $id = $_GET['unpingame'];

    $sql = "UPDATE `games` SET `priority` = '0' WHERE `games`.`id` = '$id'";
    $query_run = mysqli_query($conn, $sql);

  if ($query_run) {
    $_SESSION['status'] = "Unpinned";
    $_SESSION['message'] = "Game Unpinned";
    $_SESSION['icon'] =  'success';
    header('Location: games.php');
  } else{
      $_SESSION['status'] = "Error";
      $_SESSION['message'] = "Error ocurred!";
      $_SESSION['icon'] =  'error';
      header('Location: games.php');
  }
}









if (isset($_POST['checkbox6']['0'])) {
     
    foreach ($_POST['checkbox6'] as $row) {
       $id = mysqli_real_escape_string($conn, $row);
       $query = "DELETE FROM `badge` WHERE `id`='$id'";
       $query_run = mysqli_query($conn, $query);
    }
}


if (isset($_POST['add_avatar'])) {
    $title = filter($_POST['title']);


    $img_name = $_FILES['avatar']['name'];
    $img_size = $_FILES['avatar']['size'];
    $tmp_name = $_FILES['avatar']['tmp_name'];
    $error = $_FILES['avatar']['error'];


    if ($error === 0) {
        if ($img_size > 12000000) {
            $_SESSION['status'] = 'error';
            $_SESSION['message'] = 'Image is Large';
            header("Location: badge.php");

        } else{
            $img_ex = pathinfo($img_name, PATHINFO_EXTENSION);
            $img_ex_lc = strtolower($img_ex);

            $allowed_extensions = array('png', 'jpg', 'jpeg', );

            if (in_array($img_ex_lc, $allowed_extensions)) {
               $new_image_name = uniqid("avatar", true).'.'. $img_ex_lc;

               $img_upload_path = "uploads/avatars/".$new_image_name;

               move_uploaded_file($tmp_name, $img_upload_path);

               $path = "uploads/avatars/". $new_image_name;

            //    Insert The Data
            $sql = "INSERT INTO `avatars`(`name`, `image`) VALUES ('$title','$path')";

            $query_run = mysqli_query($conn, $sql);

            if ($query_run) {
                $_SESSION['status'] = "Created";
                $_SESSION['message'] = "Avatar Added Successfully";
                $_SESSION['icon'] =  'success';
                header('Location: avatars.php');

            } else{
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Avatar Adding Failed ['Query Error']";
                $_SESSION['icon'] =  'error';
                header('Location: avatars.php');
    

            }
            } else{
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Avatar Adding failed [USE PNG,  JPG, JPEG Files]";
                $_SESSION['icon'] =  'error';
                header('Location: avatars.php');

            }
        }
    } else {
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Avatar Adding failed ['Some Error Occured']";
        $_SESSION['icon'] =  'error';
        header('Location: avatars.php');
      

    }
}



if (isset($_POST['delete_avatar'])) {
    $id = filter($_POST['avatar_id']);
       $query = "DELETE FROM `avatars` WHERE `id`='$id'";
       $query_run = mysqli_query($conn, $query);
       if ($query_run) {
        $_SESSION['status'] = "Avatar Deleted";
        $_SESSION['message'] = "Avatar Deleted";
        $_SESSION['icon'] =  'success';
        header('Location: avatars.php');
    } else{
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Some Error Occured";
        $_SESSION['icon'] =  'error'; 
        header('Location: avatars.php');
    }
}



if (isset($_POST['checking_edit_avatar_btn'])) {
    $id = $_POST['avatar_id'];
    $result_array = [];
    $query = "SELECT * FROM `avatars` WHERE `id`='$id'";

    $query_run = mysqli_query($conn, $query);

    if (mysqli_num_rows($query_run) > 0) {
        foreach ($query_run as $row) {
           array_push($result_array, $row); 

           header('Content-Type: application/json');
           echo json_encode($result_array);
        }
    } else {
        echo $return = "<h5>No Record Found</h5>";
    }
}


if (isset($_POST['edit_avatar'])) {
    $id = filter($_POST['avatar_edit_id']);
    $oldimage = filter($_POST['oldImage']);
   
    $title = filter($_POST['avatar_name']);

    $img_name = $_FILES['avatar_image']['name'];
    $img_size = $_FILES['avatar_image']['size'];
    $tmp_name = $_FILES['avatar_image']['tmp_name'];
    $error = $_FILES['avatar_image']['error'];


   

    if ($_FILES['avatar_image']['name'] == "") {
        $image = $oldimage;
    } else{
        if ($error === 0) {
            if ($img_size > 12000000) {
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Error ocurred!";
                $_SESSION['image'] =  'error';
                header('Location: avatars.php');
    
            } else{
                $img_ex = pathinfo($img_name, PATHINFO_EXTENSION);
                $img_ex_lc = strtolower($img_ex);
    
                $allowed_extensions = array('png', 'jpg', 'jpeg');
    
                if (in_array($img_ex_lc, $allowed_extensions)) {
                   $new_image_name = uniqid("avatar", true).'.'. $img_ex_lc;
    
                   $img_upload_path = "uploads/avatars/".$new_image_name;
    
                   move_uploaded_file($tmp_name, $img_upload_path);
    
                   $path = "uploads/avatars/". $new_image_name;
                   $image = $path;
                   unlink($_POST['oldImage']);
    
                } else{
                    $_SESSION['status'] = "Error";
                    $_SESSION['message'] = "Error ocurred! [Use PNG, JPG, JPEG]";
                    $_SESSION['icon'] =  'error';
                    header('Location: avatars.php');
    
                }
            }
    }
  }

  $sql = "UPDATE `avatars` SET `name`='$title',`image`='$image' WHERE `id`='$id'";

  $query_run = mysqli_query($conn, $sql);

  if ($query_run) {
    $_SESSION['status'] = "Edited";
    $_SESSION['message'] = "Avatar Edited Successfully";
    $_SESSION['icon'] =  'success';
    header('Location: avatars.php');
  } else{
      $_SESSION['status'] = "Error";
      $_SESSION['icon'] =  'error';
      $_SESSION['message'] = "Error ocurred!";
      header('Location: avatars.php');
  }
}




if (isset($_POST['checkbox7']['0'])) {
     
    foreach ($_POST['checkbox7'] as $row) {
       $id = mysqli_real_escape_string($conn, $row);
       $query = "DELETE FROM `earninglevels` WHERE `id`='$id'";
       $query_run = mysqli_query($conn, $query);
    }
}



if (isset($_POST['delete_earning_badge'])) {
    $id = filter($_POST['delete_id']);
       $query = "DELETE FROM `earninglevels` WHERE `id`='$id'";
       $query_run = mysqli_query($conn, $query);
       if ($query_run) {
        $_SESSION['status'] = "Badge Deleted";
        $_SESSION['message'] = "Badge Deleted";
        $_SESSION['icon'] =  'success';
        header('Location: badges.php');
    } else{
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Some Error Occured";
        $_SESSION['icon'] =  'error'; 
        header('Location: badges.php');
    }
}


if (isset($_POST['add_badge'])) {
    $title = filter($_POST['title']);
    $greeting = filter($_POST['greeting']);
    $minLimit = filter($_POST['minLimit']);
    $maxLimit = filter($_POST['maxLimit']);

    $img_name = $_FILES['image']['name'];
    $img_size = $_FILES['image']['size'];
    $tmp_name = $_FILES['image']['tmp_name'];
    $error = $_FILES['image']['error'];


    if ($error === 0) {
        if ($img_size > 12000000) {
            $_SESSION['status'] = 'error';
            $_SESSION['message'] = 'Image is Large';
            header("Location: badges.php");

        } else{
            $img_ex = pathinfo($img_name, PATHINFO_EXTENSION);
            $img_ex_lc = strtolower($img_ex);

            $allowed_extensions = array('png', 'jpg', 'jpeg', );

            if (in_array($img_ex_lc, $allowed_extensions)) {
               $new_image_name = uniqid("badge", true).'.'. $img_ex_lc;

               $img_upload_path = "uploads/badges/".$new_image_name;

               move_uploaded_file($tmp_name, $img_upload_path);

               $path = "uploads/badges/". $new_image_name;

            //    Insert The Data
            $sql = "INSERT INTO `earninglevels`(`name`, `icon`, `greetings`, `minLimit`, `maxLimit`) VALUES ('$title','$path','$greeting','$minLimit','$maxLimit')";

            $query_run = mysqli_query($conn, $sql);

            if ($query_run) {
                $_SESSION['status'] = "Created";
                $_SESSION['message'] = "Badge Added Successfully";
                $_SESSION['icon'] =  'success';
                header('Location: badges.php');

            } else{
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Badge Adding Failed ['Query Error']";
                $_SESSION['icon'] =  'error';
                header('Location: badges.php');
    

            }
            } else{
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Badge Adding failed [USE PNG,  JPG, JPEG Files]";
                $_SESSION['icon'] =  'error';
                header('Location: badges.php');

            }
        }
    } else {
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Badge Adding failed ['Some Error Occured']";
        $_SESSION['icon'] =  'error';
        header('Location: badges.php');
      

    }
}



if (isset($_POST['checking_edit_badge_btn'])) {
    $id = $_POST['badge_id'];
    $result_array = [];
    $query = "SELECT * FROM `earninglevels` WHERE `id`='$id'";

    $query_run = mysqli_query($conn, $query);

    if (mysqli_num_rows($query_run) > 0) {
        foreach ($query_run as $row) {
           array_push($result_array, $row); 

           header('Content-Type: application/json');
           echo json_encode($result_array);
        }
    } else {
        echo $return = "<h5>No Record Found</h5>";
    }
}



if (isset($_POST['edit_badge'])) {
    $id = filter($_POST['badge_id_edit']);
    $oldimage = filter($_POST['oldImage']);
   
    $title = filter($_POST['badge_name']);
    $greeting = filter($_POST['greeting_edit']);
    $minLimit = filter($_POST['minLimitedit']);
    $maxLimit = filter($_POST['maxLimitedit']);

    $img_name = $_FILES['badge_image']['name'];
    $img_size = $_FILES['badge_image']['size'];
    $tmp_name = $_FILES['badge_image']['tmp_name'];
    $error = $_FILES['badge_image']['error'];


   

    if ($_FILES['badge_image']['name'] == "") {
        $image = $oldimage;
    } else{
        if ($error === 0) {
            if ($img_size > 12000000) {
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Error ocurred!";
                $_SESSION['image'] =  'error';
                header('Location: badges.php');
    
            } else{
                $img_ex = pathinfo($img_name, PATHINFO_EXTENSION);
                $img_ex_lc = strtolower($img_ex);
    
                $allowed_extensions = array('png', 'jpg', 'jpeg');
    
                if (in_array($img_ex_lc, $allowed_extensions)) {
                   $new_image_name = uniqid("badge", true).'.'. $img_ex_lc;
    
                   $img_upload_path = "uploads/badges/".$new_image_name;
    
                   move_uploaded_file($tmp_name, $img_upload_path);
    
                   $path = "uploads/badges/". $new_image_name;
                   $image = $path;
                   unlink($_POST['oldImage']);
    
                } else{
                    $_SESSION['status'] = "Error";
                    $_SESSION['message'] = "Error ocurred! [Use PNG, JPG, JPEG]";
                    $_SESSION['icon'] =  'error';
                    header('Location: badges.php');
    
                }
            }
    }
  }

  $sql = "UPDATE `earninglevels` SET `name`='$title',`icon`='$image',`greetings`='$greeting',`minLimit`='$minLimit',`maxLimit`='$maxLimit' WHERE `id`='$id'";

  $query_run = mysqli_query($conn, $sql);

  if ($query_run) {
    $_SESSION['status'] = "Edited";
    $_SESSION['message'] = "Badge Edited Successfully";
    $_SESSION['icon'] =  'success';
    header('Location: badges.php');
  } else{
      $_SESSION['status'] = "Error";
      $_SESSION['icon'] =  'error';
      $_SESSION['message'] = "Error ocurred!";
      header('Location: badges.php');
  }
}






if (isset($_POST['add_withdraw_method'])) {
    $title = filter($_POST['title']);
    $idName = filter($_POST['idName']);

    $img_name = $_FILES['icon']['name'];
    $img_size = $_FILES['icon']['size'];
    $tmp_name = $_FILES['icon']['tmp_name'];
    $error = $_FILES['icon']['error'];


    if ($error === 0) {
        if ($img_size > 12000000) {
            $_SESSION['status'] = 'error';
            $_SESSION['message'] = 'Image is Large';
            header("Location: withdraw-methods.php");

        } else{
            $img_ex = pathinfo($img_name, PATHINFO_EXTENSION);
            $img_ex_lc = strtolower($img_ex);

            $allowed_extensions = array('png', 'jpg', 'jpeg', );

            if (in_array($img_ex_lc, $allowed_extensions)) {
               $new_image_name = uniqid("withdraw-method", true).'.'. $img_ex_lc;

               $img_upload_path = "uploads/withdraw-methods/".$new_image_name;

               move_uploaded_file($tmp_name, $img_upload_path);

               $path = "uploads/withdraw-methods/". $new_image_name;

            //    Insert The Data
            $sql = "INSERT INTO `withdrawmethods`(`name`, `icon`, `idName`) VALUES ('$title','$path','$idName')";

            $query_run = mysqli_query($conn, $sql);

            if ($query_run) {
                $_SESSION['status'] = "Created";
                $_SESSION['message'] = "Withdraw Method Added Successfully";
                $_SESSION['icon'] =  'success';
                header('Location: withdraw-methods.php');

            } else{
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Withdraw Method Adding Failed ['Query Error']";
                $_SESSION['icon'] =  'error';
                header('Location: withdraw-methods.php');
    

            }
            } else{
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Withdraw Method Adding failed [USE PNG,  JPG, JPEG Files]";
                $_SESSION['icon'] =  'error';
                header('Location: withdraw-methods.php');

            }
        }
    } else {
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Avatar Adding failed ['Some Error Occured']";
        $_SESSION['icon'] =  'error';
        header('Location: withdraw-methods.php');
      

    }
}



if (isset($_POST['checking_edit_withdraw_method_btn'])) {
    $id = $_POST['method_id'];
    $result_array = [];
    $query = "SELECT * FROM `withdrawmethods` WHERE `id`='$id'";

    $query_run = mysqli_query($conn, $query);

    if (mysqli_num_rows($query_run) > 0) {
        foreach ($query_run as $row) {
           array_push($result_array, $row); 

           header('Content-Type: application/json');
           echo json_encode($result_array);
        }
    } else {
        echo $return = "<h5>No Record Found</h5>";
    }
}




if (isset($_POST['checkbox8']['0'])) {
     
    foreach ($_POST['checkbox8'] as $row) {
       $id = mysqli_real_escape_string($conn, $row);
       $query = "DELETE FROM `withdrawmethods` WHERE `id`='$id'";
       $query_run = mysqli_query($conn, $query);
    }
}




if (isset($_POST['delete_method'])) {
    $id = filter($_POST['method_id']);
       $query = "DELETE FROM `withdrawmethods` WHERE `id`='$id'";
       $query_run = mysqli_query($conn, $query);
       if ($query_run) {
        $_SESSION['status'] = "Withdraw Method Deleted";
        $_SESSION['message'] = "Withdraw Method Deleted";
        $_SESSION['icon'] =  'success';
        header('Location: withdraw-methods.php');
    } else{
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Some Error Occured";
        $_SESSION['icon'] =  'error'; 
        header('Location: withdraw-methods.php');
    }
}


if (isset($_POST['disable_method'])) {
   $id = filter($_POST['id']);

   $sql = "UPDATE `withdrawmethods` SET `enabled` = '0' WHERE `id` = '$id'";
   $query_run = mysqli_query($conn, $sql);
}
if (isset($_POST['enable_method'])) {
   $id = filter($_POST['id']);

   $sql = "UPDATE `withdrawmethods` SET `enabled` = '1' WHERE `id` = '$id'";
   $query_run = mysqli_query($conn, $sql);
}





if (isset($_POST['edit_withdraw_method'])) {
    $id = filter($_POST['method_edit_id']);
    $oldimage = filter($_POST['oldImage']);
   
    $title = filter($_POST['mehtod_name']);
    $id_name = filter($_POST['id_edit_name']);

    $img_name = $_FILES['method_image']['name'];
    $img_size = $_FILES['method_image']['size'];
    $tmp_name = $_FILES['method_image']['tmp_name'];
    $error = $_FILES['method_image']['error'];


   

    if ($_FILES['method_image']['name'] == "") {
        $image = $oldimage;
    } else{
        if ($error === 0) {
            if ($img_size > 12000000) {
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Error ocurred!";
                $_SESSION['image'] =  'error';
                header('Location: withdraw-methods.php');
    
            } else{
                $img_ex = pathinfo($img_name, PATHINFO_EXTENSION);
                $img_ex_lc = strtolower($img_ex);
    
                $allowed_extensions = array('png', 'jpg', 'jpeg');
    
                if (in_array($img_ex_lc, $allowed_extensions)) {
                   $new_image_name = uniqid("withdraw-method", true).'.'. $img_ex_lc;
    
                   $img_upload_path = "uploads/withdraw-methods/".$new_image_name;
    
                   move_uploaded_file($tmp_name, $img_upload_path);
    
                   $path = "uploads/withdraw-methods/". $new_image_name;
                   $image = $path;
                   unlink($_POST['oldImage']);
    
                } else{
                    $_SESSION['status'] = "Error";
                    $_SESSION['message'] = "Error ocurred! [Use PNG, JPG, JPEG]";
                    $_SESSION['icon'] =  'error';
                    header('Location: withdraw-methods.php');
    
                }
            }
    }
  }

  $sql = "UPDATE `withdrawmethods` SET `name`='$title',`icon`='$image',`idName`='$id_name' WHERE `id`='$id'";

  $query_run = mysqli_query($conn, $sql);

  if ($query_run) {
    $_SESSION['status'] = "Edited";
    $_SESSION['message'] = "Withdraw Method Edited Successfully";
    $_SESSION['icon'] =  'success';
    header('Location: withdraw-methods.php');
  } else{
      $_SESSION['status'] = "Error";
      $_SESSION['icon'] =  'error';
      $_SESSION['message'] = "Error ocurred!";
      header('Location: withdraw-methods.php');
  }
}

if (isset($_POST['rejectRequest'])) {
    $coins = filter($_POST['coins']);
    $id = filter($_POST['id']);
    $id_withdraw = filter($_POST['id_withdraw']);


    $sql = "UPDATE `withdrawrequests` SET `status` = '2' WHERE `id` = '$id'";
    $sql2 = "UPDATE `users` SET `coins` = `coins`+'$coins' WHERE `uId` = '$id_withdraw'";

    $sql4 = "INSERT INTO `playinghistory` (`id`, `uId`, `icon`, `activity`, `coins`, `paid`, `status`, `type`, `date`) VALUES (NULL, '$id_withdraw', '', 'Withdraw Request Rejected', '$coins', '1', '0', 'Rejected', current_timestamp())";
    
    $query_run = mysqli_query($conn, $sql);
    $query_run2 = mysqli_query($conn, $sql2);
    $query_run4 = mysqli_query($conn, $sql4) or  die("sds");

    if ($query_run && $query_run2  && $query_run4) {
        $_SESSION['status'] = "Rejected";
        $_SESSION['message'] = "Withdraw Request Rejected. The coin was refunded to the user";
        $_SESSION['icon'] =  'success';
        header('Location: withdraw-requests.php');
      } else{
          $_SESSION['status'] = "Error";
          $_SESSION['icon'] =  'error';
          $_SESSION['message'] = "Error ocurred!";
          header('Location: withdraw-requests.php');
      }

}



if (isset($_GET['withdraw_id'])) {
    $id = filter($_GET['withdraw_id']);

    $sql = "UPDATE `withdrawrequests` SET `status` = '1' WHERE `id` = '$id'";

    $query_run = mysqli_query($conn, $sql);

    if ($query_run) {
        $_SESSION['status'] = "Paid";
        $_SESSION['message'] = "Paid Successfully";
        $_SESSION['icon'] =  'success';
        header('Location: withdraw-requests.php');
      } else{
          $_SESSION['status'] = "Error";
          $_SESSION['icon'] =  'error';
          $_SESSION['message'] = "Error ocurred!";
          header('Location: withdraw-requests.php');
      }
}







if (isset($_POST['disable_ad'])) {
 
    $sql = "UPDATE `basicsettings` SET `value` = '0' WHERE `name` = 'adEnabled'";
    $query_run = mysqli_query($conn, $sql);
 }



 if (isset($_POST['enable_ad'])) {
 
    $sql = "UPDATE `basicsettings` SET `value` = '1' WHERE `name` = 'adEnabled'";
    $query_run = mysqli_query($conn, $sql);
 }



 if (isset($_POST['check_onOff'])) {
     
    $result_array = [];
     
     $sql = "SELECT * FROM `basicsettings` WHERE `name` = 'adEnabled' LIMIT 1";
     $query_run = mysqli_query($conn, $sql);
     

     foreach ($query_run as $row){
     array_push($result_array, $row); 
     }
     header('Content-Type: application/json');
      
    echo json_encode($result_array);
    
 }
 


if (isset($_POST['save_basic_settings'])) {
    $homequizcount = filter($_POST['homequizcount']);
    $dailyCheckinPrize = filter($_POST['dailyCheckinPrize']);
    $minWithdrawLimit = filter($_POST['minWithdrawLimit']);
    $maxWithdrawLimit = filter($_POST['maxWithdrawLimit']);
    $conversionRate = filter($_POST['conversionRate']);
    $firebaseKey = filter($_POST['firebaseKey']);
    $baseURL = filter($_POST['baseURL']);


    $sql1 = "UPDATE `basicsettings` SET `value` = '$homequizcount' WHERE `name` = 'Home Quiz Count'";
    $sql2 = "UPDATE `basicsettings` SET `value` = '$dailyCheckinPrize' WHERE `name` = 'Daily Check In Prize'";
    $sql3 = "UPDATE `basicsettings` SET `value` = '$minWithdrawLimit' WHERE `name` = 'Minimum Withdraw Limit';
    ";
    $sql4 = "UPDATE `basicsettings` SET `value` = '$maxWithdrawLimit' WHERE `name` = 'Maximum Withdraw Time'";
    $sql5 = "UPDATE `basicsettings` SET `value` = '$conversionRate' WHERE `name` = 'Conversion Rate'";
    $sql6 = "UPDATE `basicsettings` SET `value` = '$firebaseKey' WHERE `name` = 'Firebase Key'";
    $sql7 = "UPDATE `basicsettings` SET `value` = '$baseURL' WHERE `name` = 'Base URL'";

    $query_run1 = mysqli_query($conn, $sql1);
    $query_run2 = mysqli_query($conn, $sql2);
    $query_run3 = mysqli_query($conn, $sql3);
    $query_run4 = mysqli_query($conn, $sql4);
    $query_run5 = mysqli_query($conn, $sql5);
    $query_run6 = mysqli_query($conn, $sql6);
    $query_run7 = mysqli_query($conn, $sql7);

    if ($query_run1 && $query_run2 && $query_run3 && $query_run4 && $query_run5 && $query_run6 && $query_run7) {
        $_SESSION['status'] = "Updated";
        $_SESSION['message'] = "Setting Updated Successfully";
        $_SESSION['icon'] =  'success';
        header('Location: settings.php');
      } else{
          $_SESSION['status'] = "Error";
          $_SESSION['icon'] =  'error';
          $_SESSION['message'] = "Error ocurred!";
          header('Location: settings.php');
      }
}

if (isset($_POST['save_reward_settings'])) {
    $watchAdCoinReward = filter($_POST['watchAdCoinReward']);
    $inviteSenderReward = filter($_POST['inviteSenderReward']);
    $inviteeReward = filter($_POST['inviteeReward']);
    

    $sql1 = "UPDATE `rewardsettings` SET `value` = '$watchAdCoinReward' WHERE `name` = 'Watch Ad Coin Reward'";
    $sql2 = "UPDATE `rewardsettings` SET `value` = '$inviteSenderReward' WHERE `name` = 'Invite Sender Reward'";
    $sql3 = "UPDATE `rewardsettings` SET `value` = '$inviteeReward' WHERE `name` = 'Invitee Reward'";
   

    $query_run1 = mysqli_query($conn, $sql1);
    $query_run2 = mysqli_query($conn, $sql2);
    $query_run3 = mysqli_query($conn, $sql3);
   

    if ($query_run1 && $query_run2 && $query_run3) {
        $_SESSION['status'] = "Updated";
        $_SESSION['message'] = "Setting Updated Successfully";
        $_SESSION['icon'] =  'success';
        header('Location: settings.php');
      } else{
          $_SESSION['status'] = "Error";
          $_SESSION['icon'] =  'error';
          $_SESSION['message'] = "Error ocurred!";
          header('Location: settings.php');
      }
}


if (isset($_POST['save_ad_settings'])) {
    $nativeBannerID = filter($_POST['nativeBannerID']);
    $interstitialAd = filter($_POST['interstitialAd']);
    $rewardAdId = filter($_POST['rewardAdId']);
    

    $sql1 = "UPDATE `adsettings` SET `adId` = '$nativeBannerID' WHERE `name` = 'Native Banner Ad'";
    $sql2 = "UPDATE `adsettings` SET `adId` = '$interstitialAd' WHERE `name` = 'Interstitial Ad'";
    $sql3 = "UPDATE `adsettings` SET `adId` = '$rewardAdId' WHERE `name` = 'Rewarded Ad'";
   

    $query_run1 = mysqli_query($conn, $sql1);
    $query_run2 = mysqli_query($conn, $sql2);
    $query_run3 = mysqli_query($conn, $sql3);
   

    if ($query_run1 && $query_run2 && $query_run3) {
        $_SESSION['status'] = "Updated";
        $_SESSION['message'] = "Setting Updated Successfully";
        $_SESSION['icon'] =  'success';
        header('Location: settings.php');
      } else{
          $_SESSION['status'] = "Error";
          $_SESSION['icon'] =  'error';
          $_SESSION['message'] = "Error ocurred!";
          header('Location: settings.php');
      }
}

if (isset($_POST['send_notification'])) {
    $title = filter($_POST['title']);
    $description = filter($_POST['description']);
    $to = '/topics/NOTIFICATIONS';


    $img_name = $_FILES['image']['name'];
    $img_size = $_FILES['image']['size'];
    $tmp_name = $_FILES['image']['tmp_name'];
    $error = $_FILES['image']['error'];



    if ($error === 0) {
        if ($img_size > 12000000) {
            $_SESSION['status'] = 'error';
            $_SESSION['message'] = 'Image is Large';
            header("Location: notifications.php");

        } else{
            $img_ex = pathinfo($img_name, PATHINFO_EXTENSION);
            $img_ex_lc = strtolower($img_ex);

            $allowed_extensions = array('png', 'jpg', 'jpeg', );

            if (in_array($img_ex_lc, $allowed_extensions)) {
               $new_image_name = uniqid("notifications", true).'.'. $img_ex_lc;

               $img_upload_path = "uploads/notifications/".$new_image_name;

               move_uploaded_file($tmp_name, $img_upload_path);

               $image = "uploads/notifications/". $new_image_name;           
            } else{
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Notification Sending  failed [USE PNG,  JPG, JPEG Files]";
                $_SESSION['icon'] =  'error';
                header('Location: notifications.php');

            }
        }
    } else {
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Notification Sending failed ['Some Error Occured']";
        $_SESSION['icon'] =  'error';
        header('Location: notifications.php');
      

    }
    

    $baseSQL = "SELECT * FROM `basicsettings` WHERE `name` = 'Base URL'";

    $baseQuery_Run = mysqli_query($conn, $baseSQL);

    foreach ($baseQuery_Run as $row) {
        $baseURL = $row['value'];
    }

    $image = $baseURL.$image;


    $notification = array(
        'title' => $title,
        'body' => $description,
        'image' => $image
    );
   
   
    $data = sendNotification($to, $notification);

    if ($data == 'Success') {
        $_SESSION['status'] = "Sent";
        $_SESSION['message'] = "Notification Sent Successfully";
        $_SESSION['icon'] =  'success';
        header('Location: notifications.php');
      } else{
          $_SESSION['status'] = "Error";
          $_SESSION['icon'] =  'error';
          $_SESSION['message'] = "Error ocurred!";
          header('Location: notifications.php');
      }
}
if (isset($_POST['send_notification_to_user'])) {
    $title = filter($_POST['title']);
    $description = filter($_POST['description']);
    $uId = filter($_POST['uId']);
    $to = '/topics/'.$uId.'';


    $img_name = $_FILES['image']['name'];
    $img_size = $_FILES['image']['size'];
    $tmp_name = $_FILES['image']['tmp_name'];
    $error = $_FILES['image']['error'];



    if ($error === 0) {
        if ($img_size > 12000000) {
            $_SESSION['status'] = 'error';
            $_SESSION['message'] = 'Image is Large';
            header("Location: notifications.php");

        } else{
            $img_ex = pathinfo($img_name, PATHINFO_EXTENSION);
            $img_ex_lc = strtolower($img_ex);

            $allowed_extensions = array('png', 'jpg', 'jpeg', );

            if (in_array($img_ex_lc, $allowed_extensions)) {
               $new_image_name = uniqid("notifications", true).'.'. $img_ex_lc;

               $img_upload_path = "uploads/notifications/".$new_image_name;

               move_uploaded_file($tmp_name, $img_upload_path);

               $image = "uploads/notifications/". $new_image_name;           
            } else{
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Notification Sending  failed [USE PNG,  JPG, JPEG Files]";
                $_SESSION['icon'] =  'error';
                header('Location: notifications.php');

            }
        }
    } else {
        $_SESSION['status'] = "Error";
        $_SESSION['message'] = "Notification Sending failed ['Some Error Occured']";
        $_SESSION['icon'] =  'error';
        header('Location: notifications.php');
      

    }
    

    $baseSQL = "SELECT * FROM `basicsettings` WHERE `name` = 'Base URL'";

    $baseQuery_Run = mysqli_query($conn, $baseSQL);

    foreach ($baseQuery_Run as $row) {
        $baseURL = $row['value'];
    }

    $image = $baseURL.$image;


    $notification = array(
        'title' => $title,
        'body' => $description,
        'image' => $image
    );
   
   
    $data = sendNotification($to, $notification);

    if ($data == 'Success') {
        $_SESSION['status'] = "Sent";
        $_SESSION['message'] = "Notification Sent Successfully";
        $_SESSION['icon'] =  'success';
        header('Location: notifications.php');
      } else{
          $_SESSION['status'] = "Error";
          $_SESSION['icon'] =  'error';
          $_SESSION['message'] = "Error ocurred!";
          header('Location: notifications.php');
      }
}








if (isset($_POST['save_appinfo'])) {
    
    $privacy_policy = filter($_POST['privacy_policy']);
    $about_us = filter($_POST['about_us']);


    $sql1 = "UPDATE `appinfo` SET `description`='$privacy_policy' WHERE `name` = 'Privacy Policy'";


    $sql2 = "UPDATE `appinfo` SET `description`='$about_us' WHERE `name` = 'About Us'";
    

    $query_run1 = mysqli_query($conn, $sql1);
    $query_run2 = mysqli_query($conn, $sql2);


    if ($query_run1 && $query_run2) {
        $_SESSION['status'] = "Updated";
        $_SESSION['message'] = "App Info Updated Successfully";
        $_SESSION['icon'] =  'success';
        header('Location: appinfo.php');
    } else{
        $_SESSION['status'] = "Error";
        $_SESSION['icon'] =  'error';
        $_SESSION['message'] = "Error ocurred!";
        header('Location: appinfo.php');
    }
}



if (isset($_POST['save_admin_panel_login_details'])) {
    
    $username = filter($_POST['username']);
    $password = filter($_POST['password']);


    $sql = "UPDATE `admin_login` SET `username`='$username', `password`='$password' WHERE `id` = '1'";


   
    

    $query_run = mysqli_query($conn, $sql);
   


    if ($query_run) {
        $_SESSION['status'] = "Updated";
        $_SESSION['message'] = "Admin Panel Settings Updated Successfully";
        $_SESSION['icon'] =  'success';
        header('Location: profile.php');
    } else{
        $_SESSION['status'] = "Error";
        $_SESSION['icon'] =  'error';
        $_SESSION['message'] = "Error ocurred!";
        header('Location: profile.php');
    }
}




if (isset($_POST['save_admin_panel_settings'])) {
    

    $appName = filter($_POST['adminPanelSetting']);
    $oldIcon = filter($_POST['oldDashboardImage']);
    $oldLoginIcon = filter($_POST['oldLoginImage']);
    


    $img_name = $_FILES['newDashboardIcon']['name'];
    $img_size = $_FILES['newDashboardIcon']['size'];
    $tmp_name = $_FILES['newDashboardIcon']['tmp_name'];
    $error = $_FILES['newDashboardIcon']['error'];

    
    $login_img_name = $_FILES['newLoginIconIcon']['name'];
    $login_img_size = $_FILES['newLoginIconIcon']['size'];
    $login_tmp_name = $_FILES['newLoginIconIcon']['tmp_name'];
    $login_error = $_FILES['newLoginIconIcon']['error'];


   

    if ($_FILES['newDashboardIcon']['name'] == "") {
        $icon = $oldIcon;
    } else{
        if ($error === 0) {
            if ($img_size > 12000000) {
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Error ocurred!";
                $_SESSION['icon'] =  'error';
                header('Location: profile.php');
    
            } else{
                $img_ex = pathinfo($img_name, PATHINFO_EXTENSION);
                $img_ex_lc = strtolower($img_ex);
    
                $allowed_extensions = array('png', 'jpg', 'jpeg');
    
                if (in_array($img_ex_lc, $allowed_extensions)) {
                   $new_image_name = uniqid("admin_panel", true).'.'. $img_ex_lc;
    
                   $img_upload_path = "uploads/admin_panel/".$new_image_name;
    
                   move_uploaded_file($tmp_name, $img_upload_path);
    
                   $path = "uploads/admin_panel/". $new_image_name;
                   $icon = $path;
                   unlink($_POST['oldDashboardImage']);
    
                } else{
                    $_SESSION['status'] = "Error";
                    $_SESSION['message'] = "Error ocurred! [Use PNG, JPG, JPEG]";
                    $_SESSION['icon'] =  'error';
                    header('Location: profile.php');
    
                }
            }
    }
  }
    if ($_FILES['newLoginIconIcon']['name'] == "") {
        $icon2 = $oldLoginIcon;
    } else{
        if ($login_error === 0) {
            if ($login_img_size > 12000000) {
                $_SESSION['status'] = "Error";
                $_SESSION['message'] = "Error ocurred!";
                $_SESSION['icon'] =  'error';
                header('Location: profile.php');
    
            } else{
                $img_ex = pathinfo($login_img_name, PATHINFO_EXTENSION);
                $img_ex_lc = strtolower($img_ex);
    
                $allowed_extensions = array('png', 'jpg', 'jpeg');
    
                if (in_array($img_ex_lc, $allowed_extensions)) {
                   $new_image_name = uniqid("admin_panel", true).'.'. $img_ex_lc;
    
                   $img_upload_path = "uploads/admin_panel/".$new_image_name;
    
                   move_uploaded_file($login_tmp_name, $img_upload_path);
    
                   $path = "uploads/admin_panel/". $new_image_name;
                   $icon2 = $path;
                   unlink($_POST['oldLoginImage']);
    
                } else{
                    $_SESSION['status'] = "Error";
                    $_SESSION['message'] = "Error ocurred! [Use PNG, JPG, JPEG]";
                    $_SESSION['icon'] =  'error';
                    header('Location: profile.php');
    
                }
            }
    }
  }

  

  $sql1 = "UPDATE `basicsettings` SET `value` = '$appName' WHERE `name` = 'Admin Panel Name'";
  $sql2 = "UPDATE `basicsettings` SET `value` = '$icon' WHERE `name` = 'Dashboard Icon'";
  $sql3 = "UPDATE `basicsettings` SET `value` = '$icon2' WHERE `name` = 'Login Image'";

  $query_run1 = mysqli_query($conn, $sql1);
  $query_run2 = mysqli_query($conn, $sql2);
  $query_run3 = mysqli_query($conn, $sql3);
  
  if ($query_run1 && $query_run2 && $query_run3) {
    $_SESSION['status'] = "Updated";
    $_SESSION['message'] = "Admin Panel Settings Updated Successfully";
    $_SESSION['icon'] =  'success';
    header('Location: profile.php');
    } else{
    $_SESSION['status'] = "Error";
    $_SESSION['icon'] =  'error';
    $_SESSION['message'] = "Error ocurred!";
    header('Location: profile.php');
    }
}







?>