<?php

require 'db.php';


$postdata = file_get_contents("php://input");
$request = json_decode($postdata);

function sendNotificationMessage($title,$message,$image,$mode,$onehash,$onekey) {
    $content      = array(
        "en" => $message
    );
    if($image != "")
    {
        $fields = array(
        'app_id' => $onekey,
        //  'app_id' => "6b5ae8dd-3b56-4960-9922-f78b61e59499",
        'included_segments' => array(
            'Subscribed Users'
        ),
        'contents' => $content,
        'headings' => array("en"=>$title),
        'big_picture' => $image);
    }
    else
    {
        $fields = array(
        'app_id' => $onekey,
        'included_segments' => array(
            'Subscribed Users'
        ),
        'contents' => $content,
        'headings' => array("en"=>$title));
    }
    
    $fields = json_encode($fields);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json; charset=utf-8',
        'Authorization: Basic '.$onehash
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    return $response;
}

if(isset($postdata) && !empty($postdata))
{
    $mode = mysqli_real_escape_string($con, trim($request->mode));
    $noti_id = mysqli_real_escape_string($con, trim($request->notification_id));
    $title = mysqli_real_escape_string($con, trim($request->form_value->title));
    $message = mysqli_real_escape_string($con, trim($request->form_value->message));
    $filesource = mysqli_real_escape_string($con, trim($request->form_value->fileSource));
    $image = mysqli_real_escape_string($con, trim($request->form_value->image));
    
    $type = mysqli_real_escape_string($con, trim($request->type));
    $shop_id = mysqli_real_escape_string($con, trim($request->shop_id));
    $shop_code = mysqli_real_escape_string($con, trim($request->shop_code));
    
    include 'token_check.php';

    if($token_check)
    {
        $sel = $con->query("select one_hash,one_key from shop_settings where shop_id='$shop_id' and shop_code='$shop_code'");
        if($row = $sel->fetch_assoc())
        {
            $onehash = $row['one_hash'];
            $onekey = $row['one_key'];
        }
        
        if($mode == "add")
        {
            if($title == null ||  $title == "" || $message == null ||  $message == "")
            {
                $rows = array('status'=>false,'message' => 'Fields Missing');
                echo json_encode($rows);
            }
            else
            {
                if($filesource == null || $filesource == "")
                {
                    $sql = "INSERT INTO notification(shop_id,shop_code,title,message,send_count) VALUES ('$shop_id','$shop_code','$title','$message',0)";
                    $result = mysqli_query($con,$sql);
                    if($result)
                    {
                        $response = sendNotificationMessage($title,$message,"",$mode,$onehash,$onekey);
                        $data = json_decode($response, true);
                        if($data['id'] != null)
                        {
                            $rows = array('status'=>true,'message' => 'Notification Send Success');
                            echo json_encode($rows);
                        }
                        else
                        {
                            $rows = array('status'=>false,'message' => 'Notification Send Failure');
                            echo json_encode($rows);
                        }
                    }
                }
                else
                {
                    $url = $file_upload_url."/".$city_path."/".$cat_path."/".$shop_id;
                    $type_path = strtolower($type);
                    if (!file_exists($url . $type_path)) {
                        mkdir($url . "/" . $type_path, 0777, true);
                        $upload_url = $url. "/" .$type_path;
                    }
                    else
                    {
                        $upload_url = $url. "/" .$type_path;
                    }
    
                    $image_parts = explode(";base64,", $filesource);
                    $image_type_aux = explode("image/", $image_parts[0]);
                    $image_type = $image_type_aux[1];
                    $image_base64 = base64_decode($image_parts[1]);
                    
                    $image_file_name = uniqid(). '.png';
                    $uploadfile = $upload_url  . "/" . $image_file_name;
                    
                    $accesspath = $file_upload_extension_url. "/" .$city_path. "/" .$cat_path. "/" .$shop_id. "/";
                    $savefile = $accesspath . $type_path. "/" . $image_file_name;
    
                    file_put_contents($uploadfile, $image_base64);
                    
                    $sql = "INSERT INTO notification(shop_id,shop_code,title,image,message,send_count) VALUES ('$shop_id','$shop_code','$title','$savefile','$message',0)";
                    $result = mysqli_query($con,$sql);
                    if($result)
                    {
                        $response = sendNotificationMessage($title,$message,$savefile,$mode,$onehash,$onekey);
                        $data = json_decode($response, true);
                        if($data['id'] != null)
                        {
                            $rows = array('status'=>true,'message' => 'Notification Send Success');
                            echo json_encode($rows);
                        }
                        else
                        {
                            $rows = array('status'=>false,'message' => 'Notification Send Failure');
                            echo json_encode($rows);
                        }
                    }
                }
                
            }
        }
        
        else if($mode == "edit")
        {
            if($title == null ||  $title == "" || $message == null ||  $message == "" || $noti_id == null || $noti_id == "")
            {
                $rows = array('status'=>false,'message' => 'Fields Missing');
                echo json_encode($rows);
            }
            else
            {
                $sel = $con->query("select * from notification where id = '$noti_id' and shop_id='$shop_id' and shop_code='$shop_code'");
                if($rows = $sel->fetch_assoc())
                {
                    $sendcount = $rows['send_count'] + 1;
                    $sql = "UPDATE notification set send_count = '$sendcount' where id = '$noti_id' and shop_id='$shop_id' and shop_code='$shop_code'";
                    $result = mysqli_query($con,$sql);
                    if($result)
                    {
                        $response = sendNotificationMessage($title,$message,$image,$mode,$onehash,$onekey);
                        $data = json_decode($response, true);
                        if($data['id'] != null)
                        {
                            $rows = array('status'=>true,'message' => 'Notification Re-send Success');
                            echo json_encode($rows);
                        }
                        else
                        {
                            $rows = array('status'=>false,'message' => 'Notification Re-send Failure');
                            echo json_encode($rows);
                        }
    
                    }
                    else
                    {
                        $rows = array('status'=>false,'message' => $sendcount);
                        echo json_encode($rows);
                    }
                }
                else
                {
                    $rows = array('status'=>false,'message' => 'Notification Re-send Failure2');
                    echo json_encode($rows);
                }
                
            }
        }
        
        else if($mode == "delete")
        {
            if($noti_id == null || $noti_id == "")
            {
                $rows = array('status'=>false,'message' => 'Notification Error');
                echo json_encode($rows);
            }
            else
            {
                $sql = "DELETE FROM notification where id ='$noti_id' and shop_id='$shop_id' and shop_code='$shop_code'";
                $result = mysqli_query($con,$sql);
                if($result)
                {
                    $rows = array('status'=>true,'message' => 'Notification Deleted');
                    echo json_encode($rows);
                }
            }
        }
    
    }
    else
    {
        $rows = array('status'=>false,'message' => 'Data Error');
        echo json_encode($rows);
    }
}

?>
