<?php
include('db.php');
$json = file_get_contents('php://input');
file_put_contents('New_SMS.json', $json);

$input = file_get_contents("New_SMS.json");
parse_str($input, $output);

$Sender   = mysqli_real_escape_string($conn, $output['From']);
$Receiver = mysqli_real_escape_string($conn, $output['To']);
$Message  = mysqli_real_escape_string($conn, $output['Body']);
$Message_ID = mysqli_real_escape_string($conn, $output['MessageSid']);
date_default_timezone_set('America/New_York');
$current_date_time = date("Y-m-d H:i:s");

// Default (no image)
$ImagePath = "";

// Check if MMS has media
$numMedia = isset($output['NumMedia']) ? (int)$output['NumMedia'] : 0;

if ($numMedia > 0) {
        $i = 0;
        $mediaUrl  = $output["MediaUrl{$i}"];
        $mediaType = $output["MediaContentType{$i}"];

        // Get file extension
        $ext = explode('/', $mediaType)[1];
        $fileName = "../images/" . uniqid() . "." . $ext;
        // Fetch file with Twilio Basic Auth
        $accountSid = "AC8bac449b32a1fe6070f736d142cbac1f"; 
            $authToken  = "8e489af7dfa15b610298953e184de89d"; 
            
            $ch = curl_init($mediaUrl);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_USERPWD, "$accountSid:$authToken");  
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            $fileData = curl_exec($ch);
            
            if(curl_errno($ch)){
                echo "cURL Error: " . curl_error($ch);
            }
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($httpCode == 200 && $fileData) {
                file_put_contents($fileName, $fileData);
            }
        if ($fileData) {
            file_put_contents($fileName, $fileData);
            $ImagePath = $fileName;
        }

    $ImagePath = ltrim($ImagePath, "../images/");
}

// $Message = str_replace(['“','”'], '', $Message);
$Message = str_replace(
    ['“', '”', 'í', 'á', 'é', 'ó', 'ú', 'ñ', '’', '—'], // what to replace
    ['', '', 'i', 'a', 'e', 'o', 'u', 'n', ' ', ' '],   // replacements
    $Message
);
// Insert into DB
$Query = "INSERT INTO SMS 
    (Sender, Receiver, Body, Status, Type, Message_Id, Seen, Ping_sound, Image, created_at, updated_at)
    VALUES ('$Sender', '$Receiver', '$Message', 'Success', 'Received', '$Message_ID', '0', '0', '$ImagePath', '$current_date_time', '')";

$Insert = mysqli_query($conn, $Query);

if ($Insert) {

    // --- Send data to Send_sms.php ---
     // fetch toggle value
    $result = $conn->query("SELECT * FROM Toggle_SMS WHERE id = 1");
    $row = $result->fetch_assoc();
    $toggle_value = $row['Toggle'];
    $message_value = $row['Message'];
    
    if($toggle_value == '1'){
       // Prepare the JSON payload
        $Json_Payload = json_encode([
            'phone' => $Sender,  
            'message' => $message_value
        ]);
        
        $curl = curl_init();
        
        // Set cURL options
        curl_setopt_array($curl, [
            CURLOPT_URL => 'https://havenclean.me/haven/Chatwoot/Toggle_msg_send.php',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30, 
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $Json_Payload,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json'
            ],
        ]);
        
        // Execute the cURL request
        $response = curl_exec($curl);
        curl_close($curl);
        
    }
    // Keep your original output (do NOT change)
    echo "Inserted successfully.";

} else {
    echo "Error: " . mysqli_error($conn);
}

?>
