<?php 
require 'db-connection.php'; 
// One time password verification
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['send-otp']) && $_POST['send-otp'] == true) {
        $mobile = $_POST['mobile']; // Assuming mobile number is coming from the POST request
        $otp = generateOTP();
        
        // Send OTP and update database
        if (sendOTP($mobile, $otp)) {
            if (saveOTP($mobile, $otp, $link)) {
                echo "OTP sent successfully and saved in the database.";
            } else {
                echo "Failed to save OTP in the database.";
            }
        } else {
            echo "Failed to send OTP.";
        }
    }
    
    if (isset($_POST['verification-otp']) && $_POST['verification-otp'] == true) {
        $mobile = $_POST['mobile'];
        $entered_otp = $_POST['otp'];
        
        if (verifyOTP($mobile, $entered_otp, $link)) {
            echo "OTP verified successfully.";
        } else {
            echo "Invalid or expired OTP.";
        }
    }
}

// Function to generate a random 4-digit OTP
function generateOTP() {
    // return rand(1000, 9999);
   return mt_rand(1000, 9999);
}

// Function to send OTP via SMS
// function sendOTP($mobile, $otp) {
//     $username = 'ramhealthcare';
//     $api_key = '*VF4OT$anzQ(lp';
//     $sender = 'KYASRI';
//     $message = urlencode("Your Mobile Verification OTP is $otp, Thanks Kaya shree Ayurveda");
//     $route = 'T';
//     $entity_id = '1701173467821572189';
//     $content_id = '1707173469943285496';

//     $url = "http://shudhsms.in/sendsms_new.php?username=$username&api_key=$api_key&sender=$sender&mobile=$mobile&message=$message&route=$route&entity_id=$entity_id&content_id=$content_id";

//     // cURL request to send SMS
//     $ch = curl_init();
//     curl_setopt($ch, CURLOPT_URL, $url);
//     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//     $response = curl_exec($ch);
//     curl_close($ch);
//     return $response;
// }

function sendOTP($mobile, $otp) {
    $username = 'ramcare.trans';
    $password = 'Vq9ck';
    $sender = 'KYASRI';
    $message = urlencode("Your Mobile Verification OTP is $otp, Thanks Kaya shree Ayurveda");
    $dltContentId = '1707173469943285496';
    $unicode = 'false';
    $url = "https://trans.ncdm.in/fe/api/v1/send?username=$username&password=$password&unicode=$unicode&from=$sender&to=$mobile&text=$message&dltContentId=$dltContentId";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'cURL error: ' . curl_error($ch);
    }
    curl_close($ch);
    return $response;
}
// Function to save OTP in the database
function saveOTP($mobile, $otp, $link) {
    $expiry_time = date('Y-m-d H:i:s', strtotime('+5 minutes')); // OTP valid for 5 minutes
    $stmt = $link->prepare("INSERT INTO tbl_user (mobile, otp, expiry_time) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE otp = VALUES(otp), expiry_time = VALUES(expiry_time)");
    $stmt->bind_param('sss', $mobile, $otp, $expiry_time);

    if ($stmt->execute()) {
        return true;
    } else {
        return false;
    }
}

// Function to verify OTP from database
function verifyOTP($mobile, $entered_otp, $link) {
    $stmt = $link->prepare("SELECT otp, expiry_time FROM tbl_user WHERE mobile = ? AND otp = ?");
    $stmt->bind_param('ss', $mobile, $entered_otp);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($otp, $expiry_time);

    if ($stmt->num_rows > 0) {
        $stmt->fetch();
        if (strtotime($expiry_time) > time()) {
            return true; // OTP is valid
        } else {
            return false; // OTP has expired
        }
    } else {
        return false; // OTP not found
    }
}

// Close the database connection
$link->close();
?>
