<?php
//api.php writes the json file
function writeFile() {
  if (!isset($_COOKIE["offset"])) {
    $offset = '+00:00';
  } else {
    $offset = $_COOKIE["offset"];
  }
  // Instantiate DB & connect
 
try {
  $database = new Database();
} catch (Exception $e) {
  _log('API Says: Error new Database: ' . $e->getMessage());
  die();
}
try {
  $db = $database->connect();
} catch (Exception $e) {
  _log('API Says: Error connecting to database: ' . $e->getMessage());
  die();
}
try {
  $post = new Post($db);
} catch (Exception $e) {
  _log('API Says: Error instantiating post object: ' . $e->getMessage());
  die();
}
 $result = $post->read();

  // Get row count
  //$num = $result->rowCount(); //this doesn't work with sqlite v3 always returns 0
  $num = 1;
  if ($num > 0) {
    //  array
    $the_arr = array();
    while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
      extract($row);
      // format date-time
      $ev_start = convertToISO8601($ev_start, $offset);
      $ev_end = convertToISO8601($ev_end, $offset);
      $the_item = array(
        'id' => $id,
        'title' => $title,
        'details' => html_entity_decode($details),
        'url' => $event_url,
        'start' => str_replace("+00:00", $offset, $ev_start),
        'end' => str_replace("+00:00", $offset, $ev_end),
        'venue' => $venue,
        'venue_add' => $venue_add,
        'social_url' => $social_url,
        'sponsors' => $sponsors,
        'textColor' => $textColor,
        'borderColor' => $borderColor,
        'backgroundColor' => $backgroundColor
        // filter field here
      );
      // Push to "the_arr"
      array_push($the_arr, $the_item);
    }
    // Turn to JSON & output a file
    // multi file write by filter would go here
    $toFile = $_SESSION['sc_json']; //will need ability for more than one
    $fp = fopen($toFile, 'w');
    if (!$fp) {
      _log('api says: Error opening Json file...');
    } else {
      fwrite($fp, json_encode($the_arr));
      fclose($fp);
      _log('api says: Json File Updated and closed...');
    }
  } else {
    // No Posts
    _log('api says: No posts found...');
    echo json_encode(
      array('message' => 'No Posts Found')
    );
  }
}




//////////
function convertToISO8601($dateTimeString, $offset) {
  // determine the date-time format from UI setting
  $dateFormat = $_SESSION['format'];//options: Ymd, Ydm, mdY, dmY
  $dateSeperator = $_SESSION['separator']; //options: / - .
  if($_SESSION['hours']){ // bol
    $timeFormat = '24hr';
    list($date,$time) = explode(' ', $dateTimeString);
    }else{
    $timeFormat = '12hr';
    list($date,$time,$amPm) = explode(' ', $dateTimeString);
   }
   // convert to ISO 8601
     switch ($dateFormat) {
      case 'Ymd':
      list($year,$month, $day) = explode($dateSeperator, $date);
      $date = "$year-$month-$day";
      break;
    case 'Ydm':
      list($year, $day, $month) = explode($dateSeperator, $date);
      $date = "$year-$month-$day";
      break;
    case 'mdY':
      list($month, $day, $year) = explode($dateSeperator, $date);
      $date = "$year-$month-$day";
      break;
    case 'dmY':
      list($day, $month, $year) = explode($dateSeperator, $date);
      $date = "$year-$month-$day";
      break;
    default:
      return null;
  }
  switch ($timeFormat) {
    case '24hr':
      break;
    case '12hr':
      $hours = (int) explode(':', $time)[0];
      if ($amPm === 'PM' && $hours < 12) {
        $hours += 12;
      }
      if ($amPm === 'AM' && $hours === 12) {
        $hours = 0;
      }
      $time = sprintf('%02d:%02d', $hours, explode(':', $time)[1]);
      break;
    default:
      return null;
  }
  return $date.'T'.$time.$offset;
}
 ?>