<?php

include "config.php";

try {
    $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASSWORD);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $pdo->exec("SET time_zone = '+03:00'");

} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
    die("Error: " . $e->getMessage());
}


define("MB", 1048576);

function filterRequest($requestname)
{
  return  htmlspecialchars(strip_tags($_POST[$requestname]));
}

function getAllData($table, $where = null, $values = null)
{
    global $con;
    $data = array();
    $stmt = $con->prepare("SELECT  * FROM $table WHERE   $where ");
    $stmt->execute($values);
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $count  = $stmt->rowCount();
    if ($count > 0){
        echo json_encode(array("status" => "success", "data" => $data));
    } else {
        echo json_encode(array("status" => "failure"));
    }
    return $count;
}

function insertData($table, $data, $json = true)
{
    global $con;
    foreach ($data as $field => $v)
        $ins[] = ':' . $field;
    $ins = implode(',', $ins);
    $fields = implode(',', array_keys($data));
    $sql = "INSERT INTO $table ($fields) VALUES ($ins)";

    $stmt = $con->prepare($sql);
    foreach ($data as $f => $v) {
        $stmt->bindValue(':' . $f, $v);
    }
    $stmt->execute();
    $count = $stmt->rowCount();
    if ($json == true) {
    if ($count > 0) {
        echo json_encode(array("status" => "success"));
    } else {
        echo json_encode(array("status" => "failure"));
    }
  }
    return $count;
}


function updateData($table, $data, $where, $json = true)
{
    global $con;
    $cols = array();
    $vals = array();

    foreach ($data as $key => $val) {
        $vals[] = "$val";
        $cols[] = "`$key` =  ? ";
    }
    $sql = "UPDATE $table SET " . implode(', ', $cols) . " WHERE $where";

    $stmt = $con->prepare($sql);
    $stmt->execute($vals);
    $count = $stmt->rowCount();
    if ($json == true) {
    if ($count > 0) {
        echo json_encode(array("status" => "success"));
    } else {
        echo json_encode(array("status" => "failure"));
    }
    }
    return $count;
}

function deleteData($table, $where, $json = true)
{
    global $con;
    $stmt = $con->prepare("DELETE FROM $table WHERE $where");
    $stmt->execute();
    $count = $stmt->rowCount();
    if ($json == true) {
        if ($count > 0) {
            echo json_encode(array("status" => "success"));
        } else {
            echo json_encode(array("status" => "failure"));
        }
    }
    return $count;
}

function imageUpload($imageRequest)
{
  global $msgError;
  $imagename  = rand(1000, 10000) . $_FILES[$imageRequest]['name'];
  $imagetmp   = $_FILES[$imageRequest]['tmp_name'];
  $imagesize  = $_FILES[$imageRequest]['size'];
  $allowExt   = array("jpg", "png", "gif", "mp3", "pdf");
  $strToArray = explode(".", $imagename);
  $ext        = end($strToArray);
  $ext        = strtolower($ext);

  if (!empty($imagename) && !in_array($ext, $allowExt)) {
    $msgError = "EXT";
  }
  if ($imagesize > 2 * MB) {
    $msgError = "size";
  }
  if (empty($msgError)) {
    move_uploaded_file($imagetmp,  "../upload/" . $imagename);
    return $imagename;
  } else {
    return "fail";
  }
}



function deleteFile($dir, $imagename)
{
    if (file_exists($dir . "/" . $imagename)) {
        unlink($dir . "/" . $imagename);
    }
}

function checkAuthenticate()
{
    if (isset($_SERVER['PHP_AUTH_USER'])  && isset($_SERVER['PHP_AUTH_PW'])) {
        if ($_SERVER['PHP_AUTH_USER'] != "wael" ||  $_SERVER['PHP_AUTH_PW'] != "wael12345") {
            header('WWW-Authenticate: Basic realm="My Realm"');
            header('HTTP/1.0 401 Unauthorized');
            echo 'Page Not Found';
            exit;
        }
    } else {
        exit;
    }

    // End 
}
    function printFailure($message="none")
    {
    echo json_encode(array("status" => "failure", "message"=>$message));
    }

    function sendSms($username,$password,$msg,$numbers,$sender,$dtime){
        
        $username = urlencode($username);
        $password = urlencode($password);
        $msg = urlencode($msg);
        $numbers = urlencode($numbers);
        $sender = urlencode($sender);
        $dtime = urlencode($dtime);

        $url = "https://gosmssite.com/http.php?username=$username&password=$password&msg=$msg&texttype=unicode&numbers=$numbers&sender=$sender&dtime=$dtime";

    $response = file_get_contents($url);

    if ($response !== false) {
        echo json_encode(array("status" => "success", "message" => "SMS sent successfully"));
    } else {
        echo json_encode(array("status" => "Failed", "message" => "Failed in sending SMS. Error: " . $http_response_header[0]));
    }


    }


    // Generate OTP and timestamp
function generateOTP() {
    $otp = rand(1000, 9999); // Generate a 4-digit OTP
    $timestamp = time();    // Record the current timestamp
    return array('otp' => $otp, 'timestamp' => $timestamp);
}

// Verify OTP
function verifyOTP($userEnteredOTP, $otpData) {
    // Check if the OTP exists and is within the 10-minute validity period
    if ($otpData && isset($otpData['otp']) && isset($otpData['timestamp'])) {
        $currentTime = time();
        $otpTimestamp = $otpData['timestamp'];

        // Check if the OTP has not expired (10 minutes = 600 seconds)
        if ($currentTime - $otpTimestamp <= 600 && $userEnteredOTP == $otpData['otp']) {
            return true; // OTP is valid
        }
    }
    return false; // OTP is invalid or has expired
}

function sendKeepNotification($title, $message, $topic, $pageid, $pagename,$refreshOrder=false,$newOrder=false,$orderId)
{


    $url = 'https://fcm.googleapis.com/fcm/send';

    $fields = array(
        // "to" => '/topics/' . $topic,
        "to" => $topic,
        'priority' => 'high',
        'content_available' => true,

        'android'=> array(
            "priority"=> "HIGH",
        "notification"=> array(
           "channel_id"=> "high_importance",
            "notification_priority"=> "PRIORITY_MAX",
            "sound"=> "default",
            "default_sound"=> true,
            "default_vibrate_timing"=> true,
            "default_light_settings"=> true
        )
        ),

        'data' => array(
            "pageid" => $pageid,
            "pagename" => $pagename,
            "refresh_order"=>$refreshOrder,
            "new_order"=>$newOrder,
            "order_id"=>$orderId,
            "title"=>$title,
            "body"=>$message
        )

    );



    $fields = json_encode($fields);
    $headers = array(
        'Authorization: key=' . "AAAAQtq0tdo:APA91bFUMRW2sGInxz0zm2fZ8GBl2gpfa4xamUvggMtvJGQ6NgdEW-yMat5Vsytdkc_WTi04rAvgi8SmXIRyb_idnqSvyVFm7P5t8O7pBX7pECOjy2BJl8WzcbfD4JW-KDvN8pJpV5l4",
        'Content-Type: application/json'
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

    $result = curl_exec($ch);
    return $result;
    curl_close($ch);
}

function sendGCM($title, $message, $topic, $pageid, $pagename,$refreshOrder=false)
{


    $url = 'https://fcm.googleapis.com/fcm/send';
    // $fields = array(
    //     // "to" => '/topics/' . $topic,
    //     "to" => $topic,
    //     'priority' => 'high',
    //     'content_available' => true,

    //     "android" => array(
    //         "priority"=> "HIGH",
    //         "notification"=> array(
    //             // "body" =>  $message,
    //             // "title" =>  $title,
    //             "channel_id"=> "high_importance",
    //             "notification_priority"=> "PRIORITY_MAX",
    //             "sound"=> "default",
    //             "default_sound"=> true,
    //             "default_vibrate_timing"=> true,
    //             "default_light_settings"=> true
    //         )
    //     ),

  

         
  
    //     'data' => array(
    //         "pageid" => $pageid,
    //         "pagename" => $pagename
    //     )

    // );

    $fields = array(
        // "to" => '/topics/' . $topic,
        "to" => $topic,
        'priority' => 'high',
        'content_available' => true,

        'android'=> array(
            "priority"=> "HIGH",
        "notification"=> array(
           "channel_id"=> "high_importance",
            "notification_priority"=> "PRIORITY_MAX",
            "sound"=> "default",
            "default_sound"=> true,
            "default_vibrate_timing"=> true,
            "default_light_settings"=> true
        )
        ),

        'notification' => array(
            "body" =>  $message,
            "title" =>  $title,
            // "click_action" => "FLUTTER_NOTIFICATION_CLICK",
            "sound" => "default"
        ),
        'data' => array(
            "pageid" => $pageid,
            "pagename" => $pagename,
            "refresh_order"=>$refreshOrder
        )

    );



    $fields = json_encode($fields);
    $headers = array(
        'Authorization: key=' . "AAAAQtq0tdo:APA91bFUMRW2sGInxz0zm2fZ8GBl2gpfa4xamUvggMtvJGQ6NgdEW-yMat5Vsytdkc_WTi04rAvgi8SmXIRyb_idnqSvyVFm7P5t8O7pBX7pECOjy2BJl8WzcbfD4JW-KDvN8pJpV5l4",
        'Content-Type: application/json'
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

    $result = curl_exec($ch);
    return $result;
    curl_close($ch);
}

function nashmiSendGCM($title, $message, $topic, $pageid, $pagename)
{


    $url = 'https://fcm.googleapis.com/fcm/send';

    

    $fields = array(
        // "to" => '/topics/' . $topic,
        "to" => $topic,
        'priority' => 'high',
        'content_available' => true,

        "android" => array(
            "priority"=> "HIGH",
            "notification"=> array(
                "body" =>  $message,
                "title" =>  $title,
                "channel_id"=> "high_importance",
                "notification_priority"=> "PRIORITY_MAX",
                "sound"=> "default",
                "default_sound"=> true,
                "default_vibrate_timing"=> true,
                "default_light_settings"=> true
            )
        ),

  
        'data' => array(
            "pageid" => $pageid,
            "pagename" => $pagename
        )

    );


    $fields = json_encode($fields);
    $headers = array(
        'Authorization: key=' . "AAAABGTJZeA:APA91bFEitAU4aRElJFu1urwgh-MAUNAsNau1xFyS6lPEHDWPV4cBqWvUvL1ljYUiYxL-jRW8meTV0PCoNAUgxkwUuq58STRxBBQ5o0_s43AHjzGOe947uxpFhZIGO35T_vBddBjVSzi",
        'Content-Type: application/json'
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

    $result = curl_exec($ch);
    return $result;
    curl_close($ch);
}



function insertNotification($title,$body,$userId,$topic,$pageId,$pageName){
    global $con; 
    $stmt = $con->prepare("INSERT INTO `notifications`(`notTitle`, `notificationContent`, `notToUserId`) VALUES (?, ?, ?)");
    $stmt->execute(array($title,$body,$userId));
     sendGCM($title,$body,$topic,$pageId,$pageName);
     $count=$stmt->rowCount();
     return $count;

 }

// Example usage:
// $otpData = generateOTP(); // Generate OTP and store it with the timestamp
// // Store $otpData in your database or a cache

// // Later, when verifying the OTP (e.g., during user sign-up):
// $userEnteredOTP = 1234; // Replace with the OTP entered by the user
// if (verifyOTP($userEnteredOTP, $otpData)) {
//     // OTP is valid
// } else {
//     // OTP is either invalid or has expired
// }
