<?php 
ini_set("display_errors", 1);
header("Access-Control-Allow-Origin: *");
header("Content-type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");

require_once("../Database/Database.php");
require_once("../Classes/NUMBER.php");
require_once("../Constants/Constants_Variable.php");
include_once("../JWT/autoload.php");
include_once("../JWT/JWT.php");
include_once("../JWT/BeforeValidException.php");
include_once("../JWT/ExpiredException.php");
include_once("../JWT/SignatureInvalidException.php");
use \Firebase\JWT\JWT;
require __DIR__ . '/vendor/autoload.php';
use Twilio\Rest\Client;
use ReceiptValidator\GooglePlay\Validator as Validator;

error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
require_once __DIR__ . '/masterr/vendor/autoload.php';
require_once __DIR__ . '/masterr/library/GooglePlay/Validator.php';

$root = realpath(dirname(dirname(__FILE__)));
$library = "$root/library";
$path = array($library, get_include_path());
set_include_path(implode(PATH_SEPARATOR, $path));

$applicationName = 'mobisystems';
$scope = [Google_Service_AndroidPublisher::ANDROIDPUBLISHER];
$configLocation = 'google_service.json';

$db = new Database();
$Connection = $db->Connect();
$student = new Users($Connection);

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $data = json_decode(file_get_contents("php://input"));

    if (
        !empty($data->user_id) && !empty($data->plan) &&
        !empty($data->expiry_date) && !empty($data->purchase_date) &&
        !empty($data->number) && !empty($data->num_id) &&
        !empty($data->fcm_token) && !empty($data->p_token) &&
        !empty($data->p_num_id) && !empty($data->p_product_id)
    ) {
        try {
            $headers = getallheaders();
            if (array_key_exists('Authorization', $headers) && $headers['Authorization'] != '') {
                $token = $headers["Authorization"];
                $secret_key = "waheedkhan786";
                $decoded_data = JWT::decode($token, $secret_key, array('HS256'));
                $student->user_id = $decoded_data->data->user_id;
                $student->user_name = $decoded_data->data->user_name;
                $student->user_email = $decoded_data->data->user_email;
                $student->fcm_token = $decoded_data->data->fcm_token;
            } else {
                throwError(ACCESS_TOKEN_ERROR, "Please add headers");
            }

            // Google Play receipt validation
            $packageName = 'com.temp_number.receive_sms.second_phone.virtual_number_whatsapp';
            $productId = $data->p_num_id;
            $purchaseToken = $data->p_token;
            $client = new \Google_Client();
            
            if ($credentialsFile = checkServiceAccountCredentialsFile()) {
                $client->setAuthConfig($credentialsFile);
            } elseif (getenv('GOOGLE_APPLICATION_CREDENTIALS')) {
                $client->useApplicationDefaultCredentials();
            } else {
                echo missingServiceAccountDetailsWarning();
                return;
            }

            $client->setApplicationName($applicationName);
            $client->setAuthConfig($configLocation);
            $client->setScopes($scope);

            $purchase_status = 0;
            $validator = new Validator(new \Google_Service_AndroidPublisher($client));
            try {
                $response = $validator->setPackageName($packageName)->setProductId($productId)->setPurchaseToken($purchaseToken)->validateSubscription();
                $purchase_status = $response->getPaymentState();
            } catch (Exception $e) {
                $purchase_status = 0;
            }

            if ($purchase_status == 0) {
                throwError(ACCESS_TOKEN_ERROR, "Please resubscribe first");
            }

            // Check if the token already exists in the database
            $sqlPToken = "SELECT COUNT(*) AS num_records FROM tbl_number WHERE p_token = '$data->p_token'";
            $resultPToken = $Connection->query($sqlPToken);
            if ($resultPToken->num_rows > 0) {
                while ($rowPToken = $resultPToken->fetch_assoc()) {
                    if ($rowPToken["num_records"] > 0) {
                        throwError(ACCESS_TOKEN_ERROR, "Please resubscribe first");
                    }
                }
            }

            // Initialize Twilio client
            $sid = "AC0bd610910620e86c79b0fd36e0a7a677";
            $token = "aa8e63b8357782efab1492f0b2e61799";
            $twilio = new Client($sid, $token);

            try {
                $incoming_phone_number = $twilio->incomingPhoneNumbers->create([
                    "phoneNumber" => $data->number,
                    "smsUrl" => "https://codesteem.com/secondnoapp/APIS/Functions/reply.php",
                    "voiceUrl" => "https://codesteem.com/secondnoapp/APIS/Functions/recordcall.php"
                ]);

                $SIDNO = $incoming_phone_number->sid;

            } catch (Twilio\Exceptions\RestException $e) {
                if ($e->getStatusCode() == 400 && strpos($e->getMessage(), 'Unable to create record') !== false) {
                    $available_numbers = $twilio->availablePhoneNumbers("US")
                        ->local
                        ->read(["smsEnabled" => true, "voiceEnabled" => true], 1);

                    if (count($available_numbers) > 0) {
                        $fresh_number = $available_numbers[0]->phoneNumber;

                        $incoming_phone_number = $twilio->incomingPhoneNumbers->create([
                            "phoneNumber" => $fresh_number,
                            "smsUrl" => "https://codesteem.com/secondnoapp/APIS/Functions/reply.php",
                            "voiceUrl" => "https://codesteem.com/secondnoapp/APIS/Functions/recordcall.php"
                        ]);

                        $SIDNO = $incoming_phone_number->sid;
                        $data->number = $fresh_number; // Update the number with the fresh number
                    } else {
                        throwError(UN_SUCCESS_RESPONSE, "No available numbers from Twilio");
                    }
                } else {
                    throwError(UN_SUCCESS_RESPONSE, $e->getMessage());
                }
            }

            // Save the number and other details in the database
            $info = getdate();
            $date = $info['mday'];
            $month = $info['mon'];
            $year = $info['year'];
            $current_date = "$date-$month-$year";

            $sql122 = "INSERT INTO `tbl_number` SET `c_id` =?, `r_id`=?, `numbers`=?, `tag`=?, `status`=?, `created_at`=?, `ptag1`=?, `ptag2`=?, `ptag3`=?, `p_token`=?, `sid`=?";
            $obj122 = $Connection->prepare($sql122);
            $dd = "2";
            $ff = "Private";
            $obj122->bind_param("sssssssssss", $dd, $dd, $data->number, $ff, $current_date, $ff, $dd, $dd, $dd, $dd, $SIDNO);
            $id2 = null;
            if ($obj122->execute()) {
                $id2 = $obj122->insert_id;
            } else {
                throwError(UN_SUCCESS_RESPONSE, "Failed to Add App Data.");
            }

            $sql1223 = "INSERT INTO `tbl_product_userids` SET `user_id` =?, `product_id`=?, `number_id`=?";
            $obj1223 = $Connection->prepare($sql1223);
            $obj1223->bind_param("sss", $data->user_id, $data->p_product_id, $id2);
            if ($obj1223->execute()) {
                // Success, continue
            } else {
                throwError(UN_SUCCESS_RESPONSE, "Failed to Add App Data.");
            }

            $actual_expiry_date = date('Y-m-d', strtotime($current_date . ' + ' . $data->plan . ' days'));
            $student->user_id = $data->user_id;
            $student->plan = $data->plan;
            $student->num_id = $id2;
            $student->status = "Active";
            $student->expiry_date = $data->expiry_date;
            $student->purchase_date = $data->purchase_date;
            $student->actual_expiry_date = $actual_expiry_date;

            if ($decoded_data->data->user_id == $data->user_id && $data->fcm_token == $decoded_data->data->fcm_token) {
                if ($student->Purchase_Number()) {
                    $query = "UPDATE tbl_number SET status='Purchased', p_token='$data->p_token' WHERE n_id=$id2";
                    $result = $Connection->query($query);
                    if ($result) {
                        // Send notification
                        $stmt21 = "SELECT `fcm_token` FROM `tbl_users` WHERE user_email='muhamadusmangulzar@gmail.com'";
                        $result21 = mysqli_query($Connection, $stmt21);
                        if (mysqli_num_rows($result21) > 0) {
                            while ($row21 = mysqli_fetch_assoc($result21)) {
                                $fcmToken = $row21['fcm_token'];
                                $message = [
                                    'to' => $fcmToken,
                                    'notification' => [
                                        'title' => 'New Phone Number Purchased',
                                        'body' => "User ID: {$data->user_id} has purchased a new phone number.",
                                    ],
                                    'data' => [
                                        'user_id' => $data->user_id,
                                        'plan' => $data->plan,
                                        'number' => $data->number
                                    ]
                                ];

                                $headers = [
                                    'Authorization: key=AAAAPMCrhcs:APA91bHnXul0JtjhtAUdIYOetYYVe6yMmCs6egGw3kYfbLfXJoQMAAUeGOt3w6phzMF2Q-flBKjRIeLJnfvGnsYEmJnUHt9hPDrmQyfndBsIUkfXASnREuH3EIWRafWsRj-7jxqvOrDO',
                                    'Content-Type: application/json'
                                ];

                                $ch = curl_init('https://fcm.googleapis.com/fcm/send');
                                curl_setopt($ch, CURLOPT_POST, 1);
                                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($message));
                                $response = curl_exec($ch);
                                curl_close($ch);

                                // echo json_encode(["success" => true, "message" => "Number purchased and notification sent"]);
                                returnResponse(SUCCESS_RESPONSE, "Number Purchased.");
                            }
                        } else {
                            // echo json_encode(["success" => true, "message" => "Number purchased, no notification sent"]);
                             returnResponse(SUCCESS_RESPONSE, "Number Purchased.");
                        }
                    } else {
                        throwError(UN_SUCCESS_RESPONSE, "Failed to update number status.");
                    }
                } else {
                    throwError(UN_SUCCESS_RESPONSE, "Failed to purchase number.");
                }
            } else {
                throwError(ACCESS_DENIED_RESPONSE, "Access Denied!..");
            }
        } catch (Exception $e) {
            throwError(UN_SUCCESS_RESPONSE, $e->getMessage());
        }
    } else {
        throwError(ACCESS_DENIED_RESPONSE, "Access Denied!..");
    }
} else {
    throwError(ACCESS_DENIED_RESPONSE, "Access Denied!... Please check method.");
}
		function checkServiceAccountCredentialsFile()
{
    // service account credentials
    $app_credentials = __DIR__ . '/google_service.json';
    return file_exists($app_credentials) ? $app_credentials : false;
}

function missingServiceAccountDetailsWarning()
{
    $ret = "
    <h3 class='warn'>
      Warning: You need download your Service Account Credentials JSON from the
      <a href='http://developers.google.com/console'>Google API console</a>.
    </h3>
    <p>
      Once downloaded, move them into the root directory of this repository and
      rename them 'service-account-credentials.json'.
    </p>
    <p>
      In your application, you should set the GOOGLE_APPLICATION_CREDENTIALS environment variable
      as the path to this file, but in the context of this example we will do this for you.
    </p>";
    return $ret;
}
// Helper function to throw errors
function throwError($code, $message) {
    echo json_encode(["error" => $code, "message" => $message]);
    exit;
}
function returnResponse($code,$data)
		{
			header("content-type:application/json");
			$errorMessage=json_encode(['response'=>['status'=>$code,'result'=>$data]]);
			echo $errorMessage;
			exit;
		}
?>
