
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php

require_once 'vendor/autoload.php'; // Loads the library
use Twilio\TwiML\MessagingResponse;

$response = new MessagingResponse;
$message = $response->message("");
$message->body("The Robots are coming! Head for the hills!");
//$message->media("https://farm8.staticflickr.com/7090/6941316406_80b4d6d50e_z_d.jpg");
print $response;

$uploadDir = __DIR__ . 'uploads/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

$numMedia = isset($_POST['NumMedia']) ? (int)$_POST['NumMedia'] : 0;

if ($numMedia > 0) {
    // 2. Loop through each media attachment
    for ($i = 0; i < $numMedia; $i++) {
        $mediaUrl = $_POST["MediaUrl$i"];
        $contentType = $_POST["MediaContentType$i"]; // e.g., 'image/jpeg'
        
        // Map common content types to file extensions
        $extension = '.bin';
        if (strpos($contentType, 'image/jpeg') !== false) $extension = '.jpg';
        elseif (strpos($contentType, 'image/png') !== false) $extension = '.png';
        elseif (strpos($contentType, 'image/gif') !== false) $extension = '.gif';
        elseif (strpos($contentType, 'video/mp4') !== false) $extension = '.mp4';

        // Generate a unique filename using timestamps and index
        $filename = 'media_' . time() . '_' . $i . $extension;
        $savePath = $uploadDir . $filename;

        // 3. Download the media file using cURL
        $ch = curl_init($mediaUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Crucial: Twilio redirects to AWS S3 buckets
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        
        $fileData = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        // 4. Save the file data if download was successful (HTTP 200)
        if ($httpCode === 200 && $fileData !== false) {
            file_put_contents($savePath, $fileData);
        }
    }
}


$file = 'msg.txt';
// The new person to add to the file
$msg = $_POST['Body'] . "-" . $_POST['From'] . "--" . $numMedia;
// Write the contents to the file, 
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $msg, FILE_APPEND | LOCK_EX);
