<?php
<?php
/*
// * Create SSQL Entry from FTP delivery
// *
/*
<?xml version="1.0" encoding="utf-8"?>
<PLAYER name="RadioBOSS" version="6.2.3.2">
<TRACK ARTIST="Morcheeba" TITLE="The Sea" ALBUM="Parts of the Process" YEAR="2003" GENRE="Lush;downbeat;" COMMENT="Ripped by Winamp" FILENAME="C:\Music & Video\Morcheeba - Parts of the Process\01 - Morcheeba - The Sea.mp3" DURATION="05:49"  STARTED="2022-12-19 01:37:03" PLAYCOUNT="4" LASTPLAYED="2022-12-19 01:37:02" INTRO="0.00" OUTRO="0.00" LANGUAGE="" RATING="0" BPM="150" TAGS="" F1="" F2="" F3="" F4="" F5="" CASTTITLE="Morcheeba - The Sea" LISTENERS="0" />
<PREVTRACK><TRACK ARTIST="Metric" TITLE="Nobody Home" ALBUM="Fantasies" YEAR="2009" GENRE="Lush; Rock; Indie Rock; New Wave;" COMMENT="http://mp3caprice.com" FILENAME="C:\Music & Video\Metric - Fantasies\14_nobody-home.mp3" DURATION="03:13"  STARTED="2022-12-19 01:37:03" PLAYCOUNT="13" LASTPLAYED="2022-12-19 01:34:14" INTRO="182.68" OUTRO="1.26" LANGUAGE=" English" RATING="6" BPM="166" TAGS="" F1="" F2="" F3="" F4="" F5="" CASTTITLE="Metric - Nobody Home" /></PREVTRACK>
</PLAYER>
*/
include "mp3/check_remote_server.php";
$remote_server = checkRemoteServerStatus(
    "http://hmmm.ds.blah.net:27274/",
    19200,
    0
);
function ReturnError($code, $text)
{
        $protocol = isset($_SERVER["SERVER_PROTOCOL"])
            ? $_SERVER["SERVER_PROTOCOL"]
            : "HTTP/1.0";
        //header($protocol . ' ' . $code . ' ' . $text);
        echo "<HTML>";
        echo "<img src ='images/favpng_construction-worker-architectural-engineering-cartoon-royalty-free.png' width='200' height='240'></img><br><br>";
        echo "SERVER_PROTOCOL ERROR<BR><BR>";
        echo "Add data to SQL -." . $text . "<br><br>";
        throw Error("EXIT CODE");
        exit();
}
if ($remote_server == true) {
    // Data Processing
    $r = fopen("images/nowplaying.xml", "r");
    if ($r !== false) {
        $length = filesize("images/nowplaying.xml");
        $textXML = fread($r, $length);
        fclose($r);
    } else {
        close($r);
        ReturnError(500, "Failed to read (".$length.") bytes of XML from file XML.");
    }
 
    if($textXML =="") {
    $artist = substr(
        $textXML,
        strpos($textXML, "ARTIST=") + 8,
        strpos($textXML, " TITLE=") - strpos($textXML, "ARTIST=") - 9
    );
    $title = substr(
        $textXML,
        strpos($textXML, " TITLE=") + 8,
        strpos($textXML, " ALBUM=") - strpos($textXML, " TITLE=") - 9
    );
    $album = substr(
        $textXML,
        strpos($textXML, " ALBUM=") + 8,
        strpos($textXML, " YEAR=") - strpos($textXML, " ALBUM=") - 9
    );
 
    $exit_old = false;
 
    // note there is now num_rows  in PDO so we have to calculate a new one to get record number.
 
    } else {
        ReturnError(500, "Failed to write /read from xml."   );
    }
    try {
        $n = 0;
        $conn = new PDO( "mysql:host=$servername;dbname=$dbname",  $username, $password  );
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql =  "SELECT * FROM `played_songs` ORDER BY `datetime` DESC LIMIT 1";
        $result = $conn->query($sql); // Use query as we are returning records.
   
        $row = $result->fetch();
        $conn = null;
        } catch (PDOException $e) {
            ReturnError(500, "Failed to write /read from SQL." . $e->getMessage() );
        }
 
        if (!($artist == $row["artist"]& $title == $row("title")) )
        {
           
            $exit_old = true;
            $genre = substr(
                $textXML,
                strpos($textXML, " GENRE=") + 8,
                strpos($textXML, " COMMENT=") - strpos($textXML, " GENRE=") - 9
            );
            $comment = substr(
                $textXML,
                strpos($textXML, " COMMENT=") + 10,
                strpos($textXML, "FILENAME=") - strpos($textXML, " COMMENT=") - 12
            );
            $length = substr(
                $textXML,
                strpos($textXML, " DURATION=") + 12,
                strpos($textXML, "  STARTED=") - strpos($textXML, " DURATION=") - 13
            );
            $rating = substr(
                $textXML,
                strpos($textXML, " RATING=") + 9,
                strpos($textXML, " BPM=") - strpos($textXML, " RATING=") - 10
            );
            $bpm = substr(
                $textXML,
                strpos($textXML, " BPM=") + 6,
                strpos($textXML, " TAGS=") - strpos($textXML, " BPM=") - 7
            );
            $listeners = substr(
                $textXML,
                strpos($textXML, " LISTENERS=") + 12,
                strpos($textXML, " />") - strpos($textXML, " LISTENERS=") - 13
            );
            $t = fopen("images/nowplaying_artwork_2.png", "r");
            if ($t !== false) {
                $artwork = fread($t, filesize("images/nowplaying_artwork_2.png"));
                fclose($t);
            } else {
                fclose($t);
                ReturnError(500, "Failed to write artwork to a file.");
            }
            $base64artwork = base64_encode($artwork);
            $sql3 = "INSERT INTO `played_songs` (`song`, `artist`, `album`, `length`, `bpm`,`genre`, `listeners`,`track_user_rating`,`track_user_num`,`comment`,`ImageBase64`) VALUES ('$title','$artist', '$album', '$length', '$bpm', '$genre','$listeners','0','0', '$comment','$base64artwork') ON DUPLICATE KEY UPDATE  `listeners`='$listeners'";
            $conn = new PDO( "mysql:host=$servername;dbname=$dbname",  $username, $password  );
            $sql = "INSERT INTO `played_songs` (`song`, `artist`, `album`, `length`, `bpm`,`genre`, `listeners`,`track_user_rating`,`track_user_num`,`comment`,`ImageBase64`) VALUES ('$title','$artist', '$album', '$length', '$bpm', '$genre','$listeners','0','0', '$comment','$base64artwork')";
       
            $conn->exec($sql3);
            $conn = null;
        }
            //echo "New record created successfully";
   
 
        // note there is now num_rows  in PDO so we have to calculate a new one to get record number.
       
 
 
    } else {
        //Server disconnected
    }
?>