<?php
require_once 'Twilio/autoload.php';
include('dbconnection.php');

use Twilio\Rest\Client;
$accountSid = 'AC8bac449b32a1fe6070f736d142cbac1f';
$authToken  = '8e489af7dfa15b610298953e184de89d';
$twilio = new Client($accountSid, $authToken);

$Sender   = '+13322308524';
$Receiver = mysqli_real_escape_string($con, $_POST['receiver'] ?? '');
$Message = $_POST['body'] ?? '';
$Image_Name = '';

if(!empty($_FILES['file']['name'])){
    $Image_uniqid_Name =  uniqid(). "." . "jpeg";
    $Image_TempName = $_FILES['file']['tmp_name'];
    move_uploaded_file($Image_TempName, "images/".$Image_uniqid_Name);
}

date_default_timezone_set('America/New_York'); 
$current_date_time = date("Y-m-d H:i:s");

// send SMS
$options = ["body" => $Message, "from" => $Sender];
if(!empty($Image_uniqid_Name)){
    $options["mediaUrl"] = ["https://havenclean.me/haven/images/".$Image_uniqid_Name];
}
$message = $twilio->messages->create($Receiver, $options);

$Message = str_replace(
    ['“', '”', '‘', '’', '—', 'í', 'á', 'é', 'ó', 'ú', 'ñ'],
    ['"', '"', "'", "'", ' ', 'i', 'a', 'e', 'o', 'u', 'n'],
    $Message
);
$Message = mysqli_real_escape_string($con, $Message);
// simple insert query
$Query = "INSERT INTO SMS 
    (Sender, Receiver, Body, Status, Type, Message_Id, Seen, Ping_sound, Image, created_at, updated_at) 
    VALUES (
        '$Sender',
        '$Receiver',
        '$Message',
        'Success',
        'Send',
        '".$message->sid."',
        '1',
        '',
        '$Image_uniqid_Name',
        '$current_date_time',
        ''
    )";

if(mysqli_query($con, $Query)){
    echo json_encode(['status' => 'success']);
}else{
    echo json_encode(['status' => 'error', 'message' => mysqli_error($con)]);
}

mysqli_close($con);
?>
