<?php
date_default_timezone_set("Asia/Calcutta");
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['hub_verify_token']) && isset($_GET['hub_challenge'])) {
    $verify_token = 'tbteck_webhook';
    if ($_GET['hub_verify_token'] === $verify_token) {
        echo $_GET['hub_challenge'];
        exit();
    } else {
        http_response_code(403);
        exit();
    }
}

// Handle incoming messages
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if ($data['object'] === 'whatsapp_business_account') {
    $entry = $data['entry'][0];
    $changes = $entry['changes'][0];
    $value = $changes['value'];
    $message = $value['messages'][0];
    $from = $message['from'];
    sendReadReceipt($message['id']);
    //Send Welcome
    
    $contacts = $value['contacts'][0];
    $profile_name = $contacts['profile']['name'];
    
    $con = new mysqli('localhost', 'tbteck_shriram_matrimony', 'varahiamman1223!', 'tbteck_shriram_matrimony');
    $ph_sql = "SELECT * FROM `phone_number` WHERE `phone` = '$from'";
    $ph_res = mysqli_query($con,$ph_sql);
    while($row = mysqli_fetch_assoc($ph_res)){
        $get_phone = $row['phone'];
    }
    if($get_phone != $from){
        $s_sql = "INSERT INTO `phone_number`(`id`, `name`, `phone`, `star`, `status`, `client`, `realtime`) VALUES (NULL,'$profile_name','$from','1','Saved','919080138043',CURRENT_TIMESTAMP())";
        $s_res = mysqli_query($con,$s_sql);
    }
    
    if ($message['type'] === 'text') {
        $text = strtolower($message['text']['body']);
        $from = $message['from'];
        $timestamp = $message['timestamp'];
        if ($text === 'hi') {
            
            sendWelcomeMessage($from,$text,$timestamp);
            // sendErrorMessage($from,$input,$test);
        }
        else{
            sendErrorMessage($from,"We are unable to understand your query😪. Type *Hi* to see how can I assist you or visit our website for more details https://www.shrirammatrimony.org",$text);
        }
    }
    elseif($message['type'] === 'image'){
        $from = $message['from'];
        $media_id = $message['image']['id'];
        $phone_number_id = "398244606712673";
        $access_token = "EAAjKJ4QeIZBoBO51gdEESZCychOuaXUh4uZApcRi1uuoEwbFKKqPwi1Ou6RYIuXeVClYems4ZA5zhf14Jv59cEQBbokXbHTatvJQR2f9cg2Sqj2TbpZBtehYnnVtdYcK7ANs9soqihSp09dxkcoZAZCLcakQjDVGlbE5U9ijZAdn9laXdEgWY7wwn1ZA2ry9SKONnIQZDZD";
        
            $url = 'https://graph.facebook.com/v20.0/'.$media_id.'';
        
            $options = [
                'http' => [
                    'header'  => "Content-type: application/json\r\n" .
                                 "Authorization: Bearer " . $access_token . "\r\n",
                ],
            ];
        
            $context  = stream_context_create($options);
            $result = file_get_contents($url, false, $context);
            $res = json_decode($result,true);
            $media_url = $res['url'];
            echo $media_url;
        
        // Initialize cURL
            $ch = curl_init($media_url);
            
            // Set cURL options
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  // Return the response as a string
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);  // Follow redirects
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                "Authorization: Bearer $access_token"
            ]);
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; PHP Script)');
            curl_setopt($ch, CURLOPT_HEADER, false);
            
            $response = curl_exec($ch);
            
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (curl_errno($ch)) {
                echo 'Error: ' . curl_error($ch);
            } elseif ($http_code != 200) {
                echo "Failed to download media. HTTP Status Code: $http_code";
            } else {
                
                echo 'Response Length: ' . strlen($response) . "\n";
                $time = time();
                $file_path = 'attachment/img/'.$time.'.jpg';
                file_put_contents($file_path, $response);

                $con = new mysqli('localhost', 'tbteck_shriram_matrimony', 'varahiamman1223!', 'tbteck_shriram_matrimony');
                //Welcome Data
                $sql = "INSERT INTO `welcome_msg`(`id`, `users`, `msg`, `client`, `realtime`) VALUES (NULL,'$from','$file_path','919080138043','$time')";
                $result = $con->query($sql);
             }
            }
    elseif($message['type'] === 'document'){
            $from = $message['from'];
            $media_id = $message['document']['id'];
            $doc_name = $message['document']['filename'];
            $phone_number_id = "398244606712673";
            $access_token = "EAAjKJ4QeIZBoBO51gdEESZCychOuaXUh4uZApcRi1uuoEwbFKKqPwi1Ou6RYIuXeVClYems4ZA5zhf14Jv59cEQBbokXbHTatvJQR2f9cg2Sqj2TbpZBtehYnnVtdYcK7ANs9soqihSp09dxkcoZAZCLcakQjDVGlbE5U9ijZAdn9laXdEgWY7wwn1ZA2ry9SKONnIQZDZD";
            
                $url = 'https://graph.facebook.com/v20.0/'.$media_id.'';
            
                $options = [
                    'http' => [
                        'header'  => "Content-type: application/json\r\n" .
                                     "Authorization: Bearer " . $access_token . "\r\n",
                    ],
                ];
            
                $context  = stream_context_create($options);
                $result = file_get_contents($url, false, $context);
                $res = json_decode($result,true);
                $media_url = $res['url'];
                echo $media_url;
            
            // Initialize cURL
                $ch = curl_init($media_url);
                
                // Set cURL options
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  // Return the response as a string
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);  // Follow redirects
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
                    "Authorization: Bearer $access_token"
                ]);
                curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; PHP Script)');
                curl_setopt($ch, CURLOPT_HEADER, false);
                
                $response = curl_exec($ch);
                
                $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                if (curl_errno($ch)) {
                    echo 'Error: ' . curl_error($ch);
                } elseif ($http_code != 200) {
                    echo "Failed to download media. HTTP Status Code: $http_code";
                } else {
                    
                    echo 'Response Length: ' . strlen($response) . "\n";
                    $time = time();
                    $file_path = 'attachment/doc/'.$doc_name.'';
                    file_put_contents($file_path, $response);
    
                    $con = new mysqli('localhost', 'tbteck_shriram_matrimony', 'varahiamman1223!', 'tbteck_shriram_matrimony');
                    //Welcome Data
                    $sql = "INSERT INTO `welcome_msg`(`id`, `users`, `msg`, `client`, `realtime`) VALUES (NULL,'$from','$file_path','919080138043','$time')";
                    $result = $con->query($sql);
                 }
            }
    elseif($message['type'] === 'audio'){
            $from = $message['from'];
            $media_id = $message['audio']['id'];
            $phone_number_id = "398244606712673";
            $access_token = "EAAjKJ4QeIZBoBO51gdEESZCychOuaXUh4uZApcRi1uuoEwbFKKqPwi1Ou6RYIuXeVClYems4ZA5zhf14Jv59cEQBbokXbHTatvJQR2f9cg2Sqj2TbpZBtehYnnVtdYcK7ANs9soqihSp09dxkcoZAZCLcakQjDVGlbE5U9ijZAdn9laXdEgWY7wwn1ZA2ry9SKONnIQZDZD";
            
                $url = 'https://graph.facebook.com/v20.0/'.$media_id.'';
            
                $options = [
                    'http' => [
                        'header'  => "Content-type: application/json\r\n" .
                                     "Authorization: Bearer " . $access_token . "\r\n",
                    ],
                ];
            
                $context  = stream_context_create($options);
                $result = file_get_contents($url, false, $context);
                $res = json_decode($result,true);
                $media_url = $res['url'];
                echo $media_url;
            
            // Initialize cURL
                $ch = curl_init($media_url);
                
                // Set cURL options
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  // Return the response as a string
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);  // Follow redirects
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
                    "Authorization: Bearer $access_token"
                ]);
                curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; PHP Script)');
                curl_setopt($ch, CURLOPT_HEADER, false);
                
                $response = curl_exec($ch);
                
                $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                if (curl_errno($ch)) {
                    echo 'Error: ' . curl_error($ch);
                } elseif ($http_code != 200) {
                    echo "Failed to download media. HTTP Status Code: $http_code";
                } else {
                    
                    echo 'Response Length: ' . strlen($response) . "\n";
                    $time = time();
                    $file_path = 'attachment/audio/'.$time.'.mp3';
                    file_put_contents($file_path, $response);
    
                    $con = new mysqli('localhost', 'tbteck_shriram_matrimony', 'varahiamman1223!', 'tbteck_shriram_matrimony');
                    //Welcome Data
                    $sql = "INSERT INTO `welcome_msg`(`id`, `users`, `msg`, `client`, `realtime`) VALUES (NULL,'$from','$file_path','919080138043','$time')";
                    $result = $con->query($sql);
                 }
            }
    elseif ($message['type'] === 'button'){
            $timestamp = $message['timestamp'];
            $text = strtolower($message['button']['text']);
            if($text === "new registration"){
             sendRegisterNowMessage($from,$text,$timestamp);
            }
            if($text === "view profile"){
             sendProfileMessage($from,$text,$timestamp);
            }
            if($text === "need an help"){
             sendHelpMessage($from,$text,$timestamp);
            }
            if($text === "married"){
             sendHelpMessage($from,$text,$timestamp);
            }
            if($text === "un married"){
             sendHelpMessage($from,$text,$timestamp);
            }
    }
    elseif ($message['interactive']['button_reply']){
        $timestamp = $message['timestamp'];
        $text = strtolower($message['interactive']['button_reply']['title']);
        if($text === "register now"){
            sendRegisterNowMessage($from,$text,$timestamp);
        }
    }
    
    else{
        sendErrorMessage($from,$input,$text);
    }

    http_response_code(200);
    echo 'EVENT_RECEIVED';
}
else {
    http_response_code(404);
}

function sendWelcomeMessage($to,$text,$timestamp) {
    
    if($text != ""){
        //DB Connection
        $con = new mysqli('localhost', 'tbteck_shriram_matrimony', 'varahiamman1223!', 'tbteck_shriram_matrimony');
        //Welcome Data
        // $time = time();
        $sql = "INSERT INTO `welcome_msg`(`id`, `users`, `msg`, `client`, `realtime`) VALUES (NULL,'$to','$text','919080138043','$timestamp')";
        $result = $con->query($sql);
    }
    
    $phone_number_id = "398244606712673";
    $access_token = "EAAjKJ4QeIZBoBO51gdEESZCychOuaXUh4uZApcRi1uuoEwbFKKqPwi1Ou6RYIuXeVClYems4ZA5zhf14Jv59cEQBbokXbHTatvJQR2f9cg2Sqj2TbpZBtehYnnVtdYcK7ANs9soqihSp09dxkcoZAZCLcakQjDVGlbE5U9ijZAdn9laXdEgWY7wwn1ZA2ry9SKONnIQZDZD";

    $url = 'https://graph.facebook.com/v20.0/' . $phone_number_id . '/messages';
        $data = [
        "messaging_product" => "whatsapp",
        "to" => $to,
        "type" => "template",
        "template" => [
        "name" => "welcome",
        "language" => [
            "code" => "en"
        ],
    ]
];


    $options = [
        'http' => [
            'header'  => "Content-type: application/json\r\n" .
                         "Authorization: Bearer " . $access_token . "\r\n",
            'method'  => 'POST',
            'content' => json_encode($data),
        ],
    ];

    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);

    if($result){
        $time = time();
            $sql1 = "INSERT INTO `reply_msg`(`id`, `admin`, `msg`, `client`, `realtime`) VALUES (NULL,'919080138043','Welcome Template','$to','$time')";
            $result1 = $con->query($sql1);
        }
    if ($result === FALSE) {
        error_log('Error sending message: ' . $result);
    }
}

function sendRegisterMessage($to,$text,$timestamp) {
    
      if($text !=""){
        $con = new mysqli('localhost', 'tbteck_shriram_matrimony', 'varahiamman1223!', 'tbteck_shriram_matrimony');
        //Welcome Data
        $sql = "INSERT INTO `welcome_msg`(`id`, `users`, `msg`, `client`, `realtime`) VALUES (NULL,'$to','$text','919080138043','$timestamp')";
        $result = $con->query($sql);
    }
    
    $phone_number_id = "398244606712673";
    $access_token = "EAAjKJ4QeIZBoBO51gdEESZCychOuaXUh4uZApcRi1uuoEwbFKKqPwi1Ou6RYIuXeVClYems4ZA5zhf14Jv59cEQBbokXbHTatvJQR2f9cg2Sqj2TbpZBtehYnnVtdYcK7ANs9soqihSp09dxkcoZAZCLcakQjDVGlbE5U9ijZAdn9laXdEgWY7wwn1ZA2ry9SKONnIQZDZD";

    $url = 'https://graph.facebook.com/v20.0/' . $phone_number_id . '/messages';
    $data = [
    "messaging_product" => "whatsapp",
    "to" => $to,
    "type" => "interactive",
    "interactive" => [
        "type" => "button",
        "header" => [
            "type" => "text",
            "text" => "Shriram Matrimony"
        ],
        "body" => [
            "text" => "Since 2001 at *Matrimony Service*\n\nA newly registered jathagam has been sent to bride and groom mobiles via Sms\n\nIf you need jathagam from us we send it through Whatsapp or Email\n\nThis is only an Matrimony service no middleman commission involved, registraion fee only\n\nAfter one year you need to update your profile.\n"
        ],
        "action" => [
            "buttons" => [
                [
                    "type" => "reply", // Use 'reply' for a quick reply button
                    "reply" => [
                        "id" => "register_now",
                        "title" => "Register Now" // Display text for the button
                    ]
                ]
            ]
        ]
    ]
];

    $options = [
        'http' => [
            'header'  => "Content-type: application/json\r\n" .
                         "Authorization: Bearer " . $access_token . "\r\n",
            'method'  => 'POST',
            'content' => json_encode($data),
        ],
    ];

    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    if($result){
        $time = time();
        $sql1 = "INSERT INTO `reply_msg`(`id`, `admin`, `msg`, `client`, `realtime`) VALUES (NULL,'919080138043','Register Template','$to','$time')";
        $result1 = $con->query($sql1);
        }
    if ($result === FALSE) {
        error_log('Error sending message: ' . $result);
    }
}

function sendRegisterNowMessage($to,$text,$timestamp) {
    
      if($text !=""){
        $con = new mysqli('localhost', 'tbteck_shriram_matrimony', 'varahiamman1223!', 'tbteck_shriram_matrimony');
        //Welcome Data
        $sql = "INSERT INTO `welcome_msg`(`id`, `users`, `msg`, `client`, `realtime`) VALUES (NULL,'$to','$text','919080138043','$timestamp')";
        $result = $con->query($sql);
    }
    
    $phone_number_id = "398244606712673";
    $access_token = "EAAjKJ4QeIZBoBO51gdEESZCychOuaXUh4uZApcRi1uuoEwbFKKqPwi1Ou6RYIuXeVClYems4ZA5zhf14Jv59cEQBbokXbHTatvJQR2f9cg2Sqj2TbpZBtehYnnVtdYcK7ANs9soqihSp09dxkcoZAZCLcakQjDVGlbE5U9ijZAdn9laXdEgWY7wwn1ZA2ry9SKONnIQZDZD";

    $url = 'https://graph.facebook.com/v20.0/' . $phone_number_id . '/messages';
    $data = [
        "messaging_product" => "whatsapp",
        "to" => $to,
        "text" => ["body" => "Since 2001 at *Matrimony Service*\n\nA newly registered jathagam has been sent to bride and groom mobiles via Sms\n\nIf you need jathagam from us we send it through Whatsapp or Email\n\nThis is only an Matrimony service no middleman commission involved, registraion fee only\n\nAfter one year you need to update your profile.\n\nClick the below link to register\n\nhttps://www.shrirammatrimony.org/"]
    ];

    $options = [
        'http' => [
            'header'  => "Content-type: application/json\r\n" .
                         "Authorization: Bearer " . $access_token . "\r\n",
            'method'  => 'POST',
            'content' => json_encode($data),
        ],
    ];

    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    if($result){
        $time = time();
        $sql1 = "INSERT INTO `reply_msg`(`id`, `admin`, `msg`, `client`, `realtime`) VALUES (NULL,'919080138043','Register Now Template','$to','$time')";
        $result1 = $con->query($sql1);
        }
    if ($result === FALSE) {
        error_log('Error sending message: ' . $result);
    }
}

function sendProfileMessage($to,$text,$timestamp) {
    
      if($text !=""){
        $con = new mysqli('localhost', 'tbteck_shriram_matrimony', 'varahiamman1223!', 'tbteck_shriram_matrimony');
        //Welcome Data
        $sql = "INSERT INTO `welcome_msg`(`id`, `users`, `msg`, `client`, `realtime`) VALUES (NULL,'$to','$text','919080138043','$timestamp')";
        $result = $con->query($sql);
    }
    
    $phone_number_id = "398244606712673";
    $access_token = "EAAjKJ4QeIZBoBO51gdEESZCychOuaXUh4uZApcRi1uuoEwbFKKqPwi1Ou6RYIuXeVClYems4ZA5zhf14Jv59cEQBbokXbHTatvJQR2f9cg2Sqj2TbpZBtehYnnVtdYcK7ANs9soqihSp09dxkcoZAZCLcakQjDVGlbE5U9ijZAdn9laXdEgWY7wwn1ZA2ry9SKONnIQZDZD";

    $url = 'https://graph.facebook.com/v20.0/' . $phone_number_id . '/messages';
    $data = [
        "messaging_product" => "whatsapp",
        "to" => $to,
        "text" => ["body" => "This is our featured brides section where you can check our elite profiles.👇\n\nhttps://www.shrirammatrimony.org/#brides\n\nThis is our featured grooms section where you can check our elite profiles.👇\n\nhttps://www.shrirammatrimony.org/#grooms"]
    ];

    $options = [
        'http' => [
            'header'  => "Content-type: application/json\r\n" .
                         "Authorization: Bearer " . $access_token . "\r\n",
            'method'  => 'POST',
            'content' => json_encode($data),
        ],
    ];

    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    if($result){
        $time = time();
        $sql1 = "INSERT INTO `reply_msg`(`id`, `admin`, `msg`, `client`, `realtime`) VALUES (NULL,'919080138043','Profile Template','$to','$time')";
        $result1 = $con->query($sql1);
        }
    if ($result === FALSE) {
        error_log('Error sending message: ' . $result);
    }
}

function sendHelpMessage($to,$text,$timestamp) {
    
      if($text !=""){
        $con = new mysqli('localhost', 'tbteck_shriram_matrimony', 'varahiamman1223!', 'tbteck_shriram_matrimony');
        //Welcome Data
        $sql = "INSERT INTO `welcome_msg`(`id`, `users`, `msg`, `client`, `realtime`) VALUES (NULL,'$to','$text','919080138043','$timestamp')";
        $result = $con->query($sql);
    }
    
    $phone_number_id = "398244606712673";
    $access_token = "EAAjKJ4QeIZBoBO51gdEESZCychOuaXUh4uZApcRi1uuoEwbFKKqPwi1Ou6RYIuXeVClYems4ZA5zhf14Jv59cEQBbokXbHTatvJQR2f9cg2Sqj2TbpZBtehYnnVtdYcK7ANs9soqihSp09dxkcoZAZCLcakQjDVGlbE5U9ijZAdn9laXdEgWY7wwn1ZA2ry9SKONnIQZDZD";

    $url = 'https://graph.facebook.com/v20.0/' . $phone_number_id . '/messages';
    $data = [
        "messaging_product" => "whatsapp",
        "to" => $to,
        "text" => ["body" => "Our team will contact you soon!\n\nIn case of any emergency call this 9442209237 number.\n\n Thank you😊"]
    ];

    $options = [
        'http' => [
            'header'  => "Content-type: application/json\r\n" .
                         "Authorization: Bearer " . $access_token . "\r\n",
            'method'  => 'POST',
            'content' => json_encode($data),
        ],
    ];

    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    if($result){
        $time = time();
        $sql1 = "INSERT INTO `reply_msg`(`id`, `admin`, `msg`, `client`, `realtime`) VALUES (NULL,'919080138043','Help Template','$to','$time')";
        $result1 = $con->query($sql1);
        }
    if ($result === FALSE) {
        error_log('Error sending message: ' . $result);
    }
}

function sendErrorMessage($to,$message,$text) {
    
      if($text !=""){
        $con = new mysqli('localhost', 'tbteck_shriram_matrimony', 'varahiamman1223!', 'tbteck_shriram_matrimony');
        //Welcome Data
        $time = time();
        $sql = "INSERT INTO `welcome_msg`(`id`, `users`, `msg`, `client`, `realtime`) VALUES (NULL,'$to','$text','919080138043','$time')";
        $result = $con->query($sql);
    }
    
    $phone_number_id = "398244606712673";
    $access_token = "EAAjKJ4QeIZBoBO51gdEESZCychOuaXUh4uZApcRi1uuoEwbFKKqPwi1Ou6RYIuXeVClYems4ZA5zhf14Jv59cEQBbokXbHTatvJQR2f9cg2Sqj2TbpZBtehYnnVtdYcK7ANs9soqihSp09dxkcoZAZCLcakQjDVGlbE5U9ijZAdn9laXdEgWY7wwn1ZA2ry9SKONnIQZDZD";

    $url = 'https://graph.facebook.com/v20.0/' . $phone_number_id . '/messages';
    $data = [
        "messaging_product" => "whatsapp",
        "to" => $to,
        "text" => ["body" => $message]
    ];

    $options = [
        'http' => [
            'header'  => "Content-type: application/json\r\n" .
                         "Authorization: Bearer " . $access_token . "\r\n",
            'method'  => 'POST',
            'content' => json_encode($data),
        ],
    ];

    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);

    if ($result === FALSE) {
        error_log('Error sending message: ' . $result);
    }
}

function sendReadReceipt($id) {

    $phone_number_id = "398244606712673";
    $access_token = "EAAjKJ4QeIZBoBO51gdEESZCychOuaXUh4uZApcRi1uuoEwbFKKqPwi1Ou6RYIuXeVClYems4ZA5zhf14Jv59cEQBbokXbHTatvJQR2f9cg2Sqj2TbpZBtehYnnVtdYcK7ANs9soqihSp09dxkcoZAZCLcakQjDVGlbE5U9ijZAdn9laXdEgWY7wwn1ZA2ry9SKONnIQZDZD";

    $url = 'https://graph.facebook.com/v20.0/' . $phone_number_id . '/messages';
    $data = [
        "messaging_product" => "whatsapp",
        "status" => "read",
        "message_id" => $id
    ];

    $options = [
        'http' => [
            'header'  => "Content-type: application/json\r\n" .
                         "Authorization: Bearer " . $access_token . "\r\n",
            'method'  => 'POST',
            'content' => json_encode($data),
        ],
    ];

    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);

    if ($result === FALSE) {
        error_log('Error sending message: ' . $result);
    }
}
?>
