<?php

   error_reporting(E_ALL);
   ini_set('display_errors', 1);

   $host = 'localhost';
   $db   = 'azagcm9_9a-zag';
   $user = 'azagcm9_Aquarius';
   $pass = 'Aq1702965330079.';
   $cset = 'utf8';

   $dsn = "mysql:host=$host;dbname=$db;charset=$cset";

   $opt = array(PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'");

   $GLOBALS["pdo"] = new PDO($dsn, $user, $pass, $opt);
   
   
$sql = "SELECT ID, Song FROM _9a_song WHERE ID = ?";
$stmt = $GLOBALS["pdo"]->prepare($sql);
$stmt->execute(array(188));

   while ($song = $stmt->fetch()) {

$song = str_replace("e%", "0%", $song);
$song = str_replace("c%", "1%", $song);
$song = str_replace("v%", "2%", $song);
$song = str_replace("l%", "3%", $song);
$song = str_replace("p%", "4%", $song);
$song = str_replace("\n", "", $song);
// print_r($song["JSON"]);
$lines = explode("$",$song["Song"]);

$songOut = array();

foreach ($lines as &$line) {
    // echo str_replace("\\n", "",json_encode($row));
    // $data = str_replace("\\n", "", $row);
    // $data = str_replace("\n", "", $line);
    
    // $data = str_replace("%", "|",$data);
    // $line = explode("|",$data);
    $segment = explode("%", $line);
    $out = array();
    // $out[] = str_replace("\\n", "", $segment[0]);
    $type = intval($segment[0]);
    $out[] = $type;

    $skip = true;
    foreach ($segment as &$item) {
       if($skip) { $skip = false; continue; }
       $chords = explode("|", $item); 
       $chord = array();
       if($type > 0) {
          foreach ($chords as &$ch) {
              $chord[] = $type == 1 ? intval($ch) : $ch; 
          }
          $out[] = $chord;
       }
    }
    $songOut[] = $out;
}
// print("<pre>".print_r($songOut,true)."</pre>");
// echo json_encode($songOut, JSON_PRETTY_PRINT);
$sqlx = "UPDATE _9a_song SET JSON = ? WHERE ID = ?";
$stmtx = $GLOBALS["pdo"]->prepare($sqlx);
$stmtx->execute(array(json_encode($songOut), $song["ID"]));
   }
?>
