#!/usr/bin/php
<?php
  /*
   * tools
   * tools/ydbcreateform
   * YeAPF 0.8.61-173 built on 2018-12-12 17:54 (-2 DST)
   * Copyright (C) 2004-2018 Esteban Daniel Dortta - dortta@yahoo.com
   * 2018-05-30 11:21:05 (-2 DST)
   *
   * Purpose: create .form .html .js and .php CRUD files
   */

  function displayError($errMessage)
  {
    global $args;

    if (is_writable('./')) {
      $f=fopen("ydbmigrate.lasterror","w");
      fwrite($f,$errMessage);
      fclose($f);
    }

    $args->setArgValue('help',__TRUE__);
    die("\n$errMessage\n");
  }

  echo basename("tools/ydbcreateform")."\nYeAPF 0.8.61 tools\nCopyright (C) 2004-2018 Esteban Daniel Dortta - dortta@yahoo.com\n\n";

  $mydir=dirname($_SERVER['SCRIPT_FILENAME']);
  (@include_once "$mydir/yclilib.php") or die("yclilib.php not found\n");
  (@include_once "$mydir/ydblib.php") or die("ydblib.php not found\n");

  $cwd=getcwd();
  $args = new ArgumentsProcessor();
  if (($args->argValue('h;help')==true) || ($args->optionCount()==0)) {
    echo "usage:";
    echo "\n\t[--db <host:database name>]\tdatabase identification";
    echo "\n\t[--user <user name>]\t\tdatabase user name";
    echo "\n\t[--pass <user password>]";
    echo "\n\t[--type <mysql|firebird|postgresql>]";
    echo "\n\t[--table <table name>]\t\tname of the table to be used";
    echo "\n\t[--sql '<select statement|sql text file>']\tsql command to export data.  Cannot be used with 'table' or 'import' options";
    echo "\n\t[--name '<output-filename>']\tit is mandatory if using --sql ";
    echo "\n\t[--folder <folder name>]\t\tfolder to be used to generate the files (defaults to 'forms')";
    die("\n");
  }

  getDBArgs($args);
  $formName=$args->argValue('name', $dbTable);
  
  $folder=$args->argValue('folder', getcwd().'/forms/');

  $dbConnect=0;

  _LOAD_YEAPF_();
  if (db_connect($dbType, $dbHost, $dbName, $dbUser, $dbPass)) {
    $dbFieldList=array();
    if ((isset($dbTable)) && ($dbTable>"")) {
      $dbFieldListAux=db_fieldList($dbTable);
    } else {
      preg_match_all("/(from|into|update|join) [\\'\\´]?([a-zA-Z0-9_-]+)[\\'\\´]?/i",
            $dbSQL, $matches);
      $dbFieldListAux = array();
      if (isset($matches[2])) {
        foreach($matches[2] as $k=>$_tableName) {
          $aux=db_fieldList($_tableName);
          foreach($aux as $k=>$v) 
            $dbFieldListAux[count($dbFieldListAux)]=$v;
        }
      }

      if ($formName=='')
        die("\nYou need to indicate form-name\n");
    }

    foreach($dbFieldListAux as $k=>$v) {
      $aux=array();
      if ($v[1]=='enum') {
        $aux['values']=$v[2];
        $v[1]="CHAR";
      } else if (strpos($v[1], 'CHAR')!==FALSE) {
        $aux['width']=$v[2];
        $v[1]="CHAR";
      }

      $aux['type']=$v[1];

      if ($v[5]=='PRI')
          $aux['PRI']=true;

      $dbFieldList[$v[0]]=$aux;
    }

    $specFieldData="placeholder='dd/mm/aaaa' editmask='dd/mm/yyyy' storagemask='yyyymmdd' valuetype='date'";

    if (is_dir($folder)) {
      if (is_writable($folder)) {
        global $__yeapfPath;
        $__yeapfPath_tools="$__yeapfPath/tools/";
        if (!is_dir("$folder/js"))
          mkdir("$folder/js", 0777, true);
        $frmBody="";
        $tBody="";
        $tHead="";
        $primaryKey="";
        $primaryType="";
        $fieldList="";
        $formFieldList="";
        foreach($dbFieldList as $fName=>$fDef) {
          $specField='';
          if ($fDef['type']=='date')
              $specField=$specFieldData;
          $frmBody.="<div class='form-group col-md-6'><label for='frm_$formName"."_$fName'>$fName</label><input type='text' class='form-control' id='frm_$formName"."_$fName' $specField /></div>";
          $tBody.="<td>%($fName)</td>";
          $tHead.="<th>$fName</th>";
          if (isset($fDef['PRI'])) {
            if ($primaryKey>'')
              displayError("ERROR: You cannot have two or more primary primaryKey");
            $primaryKey.="$fName";
            $primaryType=$fDef['type'];
          }
          if ($fieldList>'') {
            $fieldList.=", ";
            $formFieldList.=",\n";
          }
          $fieldList.=$fName;
          $formFieldList.="$fName: ".$fDef['type'];
        }

        $tHead="<tr>$tHead<th colspan=2></th></tr>";
        $tBody="<tr>$tBody<td><a class='btn btn-default' type='button' href='javascript:#(formName).editTableItem(%(rowid))'><span class='fa fa-edit'></span></a></td><td><a class='btn btn-default' type='button' href='javascript:#(formName).deleteTableItem(%(rowid))'><span class='fa fa-remove' style='color:#900'></span></a></td></tr>";

        $html=analisarString(join("",file("$__yeapfPath_tools/ydbcreateform_files/crud.html")));
        file_put_contents("$folder/f_$formName.html", $html);

        $js=analisarString(join("",file("$__yeapfPath_tools/ydbcreateform_files/script.js")));
        file_put_contents("$folder/js/$formName.js", $js);

        $php=analisarString(join("",file("$__yeapfPath_tools/ydbcreateform_files/script.php")));
        file_put_contents("$folder/$formName.php", $php);

        $form=analisarString(join("",file("$__yeapfPath_tools/ydbcreateform_files/table.form")));
        file_put_contents("$folder/$formName.form", $form);

        $json=suggestFormFromTable($dbFieldListAux);
        file_put_contents("$folder/$formName.json", $json);

      } else
        displayError("Impossible to write to '$folder' directory");
    } else
      displayError("Was not possible to found '$folder' directory");

  } else
    die("Was not possible to connect to $dbHost:$dbUser@$dbName ($dbType)");

?>