<?php

/**
 * LazyMePHP
 * @copyright This file is part of the LazyMePHP developed by Duarte Peixinho
 * @author Duarte Peixinho
 */

use \LazyMePHP\Config\Internal\APP;
use \LazyMePHP\Helper;

require_once __DIR__.'/databasehelper';
require_once __DIR__.'/../src/Configurations/Configurations.php';
require_once __DIR__.'/classesbuilder';
require_once __DIR__.'/formsbuilder';
require_once __DIR__.'/apibuilder';
require_once __DIR__.'/helper';

function enableLogging() {
  // Create Activity Log Structure if Needed
  if (APP::APP_ACTIVITY_LOG()) {
    $queryString = "
    CREATE TABLE IF NOT EXISTS `__LOG_ACTIVITY` (
    `id` int(255) NOT NULL,
    `date` datetime NOT NULL,
    `user` varchar(255) DEFAULT NULL,
    `method`varchar(10) DEFAULT NULL);
    CREATE TABLE IF NOT EXISTS `__LOG_ACTIVITY_OPTIONS` (
    `id` int(255) NOT NULL,
    `id_log_activity` int(255) NOT NULL,
    `subOption` varchar(255) NOT NULL,
    `value` varchar(255) NOT NULL);
    CREATE TABLE IF NOT EXISTS `__LOG_DATA` (
    `id` int(255) NOT NULL,
    `id_log_activity` int(255) NOT NULL,
    `table` varchar(255) NOT NULL,
    `pk` varchar(255) NULL,
    `method` varchar(1) NULL,
    `field` varchar(255) NOT NULL,
    `dataBefore` varchar(255) NULL,
    `dataAfter` varchar(255) NULL);
    ALTER TABLE `__LOG_ACTIVITY`
    ADD PRIMARY KEY (`id`);
    ALTER TABLE `__LOG_ACTIVITY_OPTIONS`
    ADD PRIMARY KEY (`id`),
    ADD KEY `id_log_activity` (`id_log_activity`);
    ALTER TABLE `__LOG_DATA`
    ADD PRIMARY KEY (`id`),
    ADD KEY `id_log_activity` (`id_log_activity`);
    ALTER TABLE `__LOG_ACTIVITY`
    MODIFY `id` int(255) NOT NULL AUTO_INCREMENT;
    ALTER TABLE `__LOG_ACTIVITY_OPTIONS`
    MODIFY `id` int(255) NOT NULL AUTO_INCREMENT;
    ALTER TABLE `__LOG_DATA`
    MODIFY `id` int(255) NOT NULL AUTO_INCREMENT;
    ALTER TABLE `__LOG_ACTIVITY_OPTIONS`
    ADD CONSTRAINT `__LOG_ACTIVITY_OPTIONS_ibfk_1` FOREIGN KEY (`id_log_activity`) REFERENCES `__LOG_ACTIVITY` (`id`);
    ALTER TABLE `__LOG_DATA`
    ADD CONSTRAINT `__LOG_DATA_ibfk_1` FOREIGN KEY (`id_log_activity`) REFERENCES `__LOG_ACTIVITY` (`id`);
    ";
    APP::DB_CONNECTION()->Query($queryString, $sqlObj);
    APP::DB_CONNECTION()->Close();
    echo "Done enabling logging, press enter to continue...";
    \LazyMePHP\Helper\read();
  }
}

// Read All Tables From Database
$queryString = "";
switch (APP::DB_TYPE())
{
  case 1: // MSSQL
    $queryString = "SELECT [Table] FROM (SELECT TABLE_NAME as [Table] FROM INFORMATION_SCHEMA.TABLES) SCH WHERE [Table] NOT LIKE '\_\_%'";
    break;
  case 2: // MYSQL
    $queryString = "SELECT `Table` FROM (SELECT DISTINCT TABLE_NAME as `Table` FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='".APP::DB_NAME()."') SCH WHERE `Table` NOT LIKE '\_\_%'";
    break;
  case 3: // SQLITE
    $queryString = "SELECT name as `Table` FROM sqlite_master WHERE type='table' and name not like '#__%' ESCAPE '#' ORDER BY name";
    break;
}

// Fetch all tables descriptors
APP::DB_CONNECTION()->Query($queryString, $sqlObj);
$tables = array();
$tablesDescriptors = array();
$i = 1;
while ($o=$sqlObj->FetchObject()) {
  $table = new \LazyMePHP\DatabaseHelper\_DB_TABLE($o->Table);
  $table->GetFieldsFromDB();
  $tableDescriptorSelected = false;
  foreach($table->GetTableFields() as $field)
  {
    if (!$field->IsPrimaryKey() && !$field->HasForeignKey()) {
      $tableDescriptorSelected = $field->GetName();
      break;
    }
  }
  if (!$tableDescriptorSelected) $tableDescriptorSelected = $table->GetPrimaryFieldName();
  $tables[] = $o->Table;
  $tablesDescriptors[$o->Table] = $tableDescriptorSelected;
}

// Check if descriptor file exists
if (!is_file(__DIR__."/.descriptors")) {
  // if not create one
  \LazyMePHP\Helper\TOUCH(__DIR__."/.descriptors");
  // and generate first version
  $tablesDescriptorsFile = fopen(__DIR__."/.descriptors","w");
  fwrite($tablesDescriptorsFile, json_encode($tablesDescriptors));
  fclose($tablesDescriptorsFile);
} 

// open file
$tablesDescriptorsFile = fopen(__DIR__."/.descriptors", "r");
$json = fread($tablesDescriptorsFile,filesize(__DIR__."/.descriptors"));
$tablesDescriptorsFromFile = json_decode($json, true);
// Update tablesDescriptors
foreach($tablesDescriptors as $t => $d) {
  if (key_exists($t, $tablesDescriptorsFromFile)) {
    $tablesDescriptors[$t] = $tablesDescriptorsFromFile[$t];
  }
}

$option = -1;
while (strlen($option)>0) {


  \LazyMePHP\Helper\printselect("Tables", $tables, null, $tablesDescriptors);
  echo "\nSelect your option:\n\n";
  echo "Build Classes: [c]\n";
  echo "Build Forms: [f]\n";
  echo "Build API: [a]\n";
  echo "Change Descriptor: [d]\n";
  echo "Enable Logging: [e]\n";
  echo "Quit: [q]\n";
  echo ":";
  $option = \LazyMePHP\Helper\read();
  if (strtolower($option) == 'd') {
    $descriptor = \LazyMePHP\Helper\select("Select Table to change descriptor", $tables, null, false, $tablesDescriptors);
    if ($descriptor) {
      $table = new \LazyMePHP\DatabaseHelper\_DB_TABLE($descriptor['name']);
      $table->GetFieldsFromDB();
      $fields = array();
      foreach($table->GetTableFields() as $f) $fields[] = $f->GetName();
      $sel = \LazyMePHP\Helper\select("Select field", $fields, $tablesDescriptors[$descriptor['name']],false);
      $tablesDescriptors[$descriptor['name']] = $sel['name'];

      $tablesDescriptorsFile = fopen(__DIR__."/.descriptors","w");
      fwrite($tablesDescriptorsFile, json_encode($tablesDescriptors));
      fclose($tablesDescriptorsFile);
    }
  } else if (strtolower($option) == 'e') {
    enableLogging();
  }
  else if (strtolower($option) == 'c') {
    buildClasses();
  }
  else if (strtolower($option) == 'f') {
    BuildForms();
  }
  else if (strtolower($option) == 'a') {
    buildAPI();
  }
  else if (strtolower($option) == 'q') {
    echo "Exiting ...";
    exit();
  }
  else $option = -1;
}

// Classes
function buildClasses() {
  global $tables;
  global $tablesDescriptors;
  $classes = \LazyMePHP\Helper\select("Select Tables to build classes", $tables, null, true, $tablesDescriptors);
  if ($classes) {
    \LazyMePHP\Helper\clear();
    echo "Tables selected for building classes:\n\n";
    echo "\nTable name\n";
    foreach($classes as $c) echo $c['name']."\n";
    $replaceI = null;
    while($replaceI === null) $replaceI = \LazyMePHP\Helper\promptYesNo("\nReplace includes.php");
    $proceed = null;
    while($proceed === null) $proceed = \LazyMePHP\Helper\promptYesNo("Do you want to continue");
    if ($proceed) {
      $tablesList = array();
      foreach($classes as $c) $tablesList[] = $c['name'];
      new \LazyMePHP\ClassesBuilder\BuildTableClasses('src/Classes', $tablesList, $replaceI, $tablesDescriptors);
    }
  }
  echo "\nDone, press enter to finish...";
  \LazyMePHP\Helper\read();
}
// Forms
function BuildForms() {
  global $tables;
  global $tablesDescriptors;
  \LazyMePHP\Helper\clear();
  $forms = \LazyMePHP\Helper\select("Select Tables to build forms", $tables, null, true, $tablesDescriptors);
  if ($forms) {
    \LazyMePHP\Helper\clear();
    echo "Tables selected for building forms:\n\n";
    echo "\nTable name\n";
    foreach($forms as $f) echo $f['name']."\n";
    echo "\n";
    $replaceR = \LazyMePHP\Helper\promptYesNo("Replace RouteForms");
    $buildViews = \LazyMePHP\Helper\promptYesNo("Build Views");
    $proceed = \LazyMePHP\Helper\promptYesNo("Proceed");
    if ($proceed) {
      $tablesList = array();
      foreach($forms as $c) $tablesList[] = $c['name'];
      new \LazyMePHP\FormsBuilder\BuildTableForms('src/Controllers', 'src/Views', 'src/Classes', 'src/Routes', $tablesList, $replaceR == 'Y', $buildViews == 'Y');
    }
  }
  echo "\nDone, press enter to finish...";
  \LazyMePHP\Helper\read();
}
// API
function buildAPI() {
  global $tables;
  global $tablesDescriptors;
  $api = \LazyMePHP\Helper\select("Select Tables to build API", $tables, null, true, $tablesDescriptors);
  if ($api) {
    \LazyMePHP\Helper\clear();
    echo "Tables selected for building API:\n\n";
    echo "\nTable name\n";
    foreach($api as $a) echo $a['name']."\n";
    $replaceA = false;
    while(strtoupper($replaceA) != "Y" && strtoupper($replaceA) != 'N') {
      echo "\nReplace RouteAPI.php? Y\\n: ";
      $proceed = trim(fgets(STDIN));
      if (!$replaceA) $replaceA = 'Y';
    }
    $proceed = null;
    while($proceed === null) $proceed = \LazyMePHP\Helper\promptYesNo("Do you want to continue");
    if ($proceed) {
      $tablesList = array();
      foreach($api as $c) $tablesList[] = $c['name'];
      new \LazyMePHP\FormsBuilder\BuildTableAPI('src/api', $replaceA=='Y', $tablesList);

    }
  }
  echo "\nDone, press enter to finish...";
  \LazyMePHP\Helper\read();
}

?>

