<?php
 session_start();
include ('connection.php') ;

if (!isset($_SESSION['is_logged_in'])) {
    header("Location:login.php");
    die();
    }
// Database credentials
$servername = "localhost";
$username = "crmsahavasco";
$password = "sa123AWEsadfa";
$dbname = "crmsahavasco_kanakveda";


include ('connection.php') ;

$querylogin = "select * from  users where username = '". $_SESSION["LOGIN_NAME"]."' AND password = '".$_SESSION["EMPLOYEE_PASSWORD"]."'";
$resultlogin = mysqli_query($conn,$querylogin);
while($row=mysqli_fetch_array($resultlogin))
{
$user_id = $row['user_id'];
$first_name = $row['first_name'];
$login_type=$row['login_type'];
echo $mobileno = $row['mobileno'];
}
echo $Customer_PhNo = $_REQUEST['Customer_PhNo'];



// Function to make a cURL request
function makeCurlRequest($url, $method, $postData = null, $headers = []) {
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_POSTFIELDS => $postData,
        CURLOPT_HTTPHEADER => $headers
    ]);
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if ($err) {
        die("cURL Error #:" . $err);
    }
    
    return $response;
}

// Step 1: Start the call
$startCallUrl = "https://api.exotel.com/v1/Accounts/sahavastechnologies1/Calls/connect.json";
$startCallPostData = [
    'From' => $mobileno,
    'To' => $Customer_PhNo,
    'CallerId' => $callerId
];
$headers = [
    "Authorization: Basic ZGY5NTgwMWRlY2Y2MzRjODNmNmZjOWUyNTRmOWRmOWNlOWZkMDY3NWQ1Nzg1MGRlOjc2Y2RhZjI2MmFjZDk3ZDFjNGJhNTVjODc1YzU4YWE4OGE5OTgxNGNkZGUzN2ZiNw==",
    "accept: application/json"
];

$response = makeCurlRequest($startCallUrl, "POST", $startCallPostData, $headers);
$data = json_decode($response, true);

$callSid = $data['Call']['Sid'];
$accountSid = $data['Call']['AccountSid'];

// Step 2: Poll the API for call status until it’s no longer "in-progress"
$callCompleted = false;
while (!$callCompleted) {
    sleep(5); // Wait for 5 seconds before polling again
    
    $checkCallStatusUrl = "https://api.exotel.com/v1/Accounts/{$accountSid}/Calls/{$callSid}.json";
    $response = makeCurlRequest($checkCallStatusUrl, "GET", null, $headers);
    $callData = json_decode($response, true);
    
    if ($callData['Call']['Status'] !== "in-progress") {
        $callCompleted = true;
    }
}

// Step 3: Extract the relevant fields from the completed call data
$call = $callData['Call'];
$sid = $call['Sid'];
$parentCallSid = $call['ParentCallSid'];
$dateCreated = $call['DateCreated'];
$dateUpdated = $call['DateUpdated'];
$to = $call['To'];
$from = $call['From'];
$phoneNumberSid = $call['PhoneNumberSid'];
$status = $call['Status'];
$startTime = $call['StartTime'];
$endTime = $call['EndTime'];
$duration = $call['Duration'];
$price = $call['Price'];
$direction = $call['Direction'];
$answeredBy = $call['AnsweredBy'];
$forwardedFrom = $call['ForwardedFrom'];
$callerName = $call['CallerName'];
$uri = $call['Uri'];
$recordingUrl = $call['RecordingUrl'];

// Step 4: Create connection to the database
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Prepare and bind
$stmt = $conn->prepare("INSERT INTO call_logs (sid, parent_call_sid, date_created, date_updated, account_sid, `to`, `from`, phone_number_sid, status, start_time, end_time, duration, price, direction, answered_by, forwarded_from, caller_name, uri, recording_url) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssssssssssssssss", $sid, $parentCallSid, $dateCreated, $dateUpdated, $accountSid, $to, $from, $phoneNumberSid, $status, $startTime, $endTime, $duration, $price, $direction, $answeredBy, $forwardedFrom, $callerName, $uri, $recordingUrl);

// Execute the prepared statement
if ($stmt->execute()) {
    echo "New record created successfully";
} else {
    echo "Error: " . $stmt->error;
}

// Close statement and connection
$stmt->close();
$conn->close();
?>
