<?php

namespace Steps;

use \ActionData;
use \db;

class PrepareLocalRecords extends AbstractStep
{
    private $db;

    private $newLine = "\n";
    private $space = "\t";

    public function __construct(\DataContainers\ActionData $actionData, \DataContainers\CurrentVersion $versions, db $db)
    {
          $this->db = $db;
          $this->actionData = $actionData;
          $this->versions = $versions;
    }

    public function execute()
    {
        $currentProject = $this->projects->current();
        $id_user = config('user_id');

        $this->recordsData = array();

        if ($currentProject && $id_user)
        {

          $sql = "SELECT id,proj_name FROM ".DB_WARPIT_WEBCATI_BASE."._Projects WHERE id = ". $currentProject;

          $res = $this->db->SQLexecute($sql);
          $zad = $this->db->fetchAssoc($res);
          $projectName = $zad['proj_name'];
          $projectId = $zad['id'];

          // visits

          $sql = "SELECT * FROM ".DB_WARPIT_WEBCATI_BASE."._Capi_interviewer_visits
                WHERE user_id = ".$id_user. " AND ( flag_cli IS NULL OR flag_cli != 1 ) AND id_project = " . $currentProject;

          $res = $this->db->SQLexecute($sql);

          $tb = DB_WARPIT_WEBCATI_BASE."._Capi_interviewer_visits";

          while ($zad = $this->db->fetchAssoc($res)) {
        //    $this->clientRequest->addRecord($tb, $zad['id'], $projectName);
            $this->addRecord(array('table' => $tb, 'id_record' => $zad['id'], 'project_name' => $projectName));

            $this->uploadUpdateDefine[$tb][] = $zad['id'];
            $list = array();

            $record .= "<record>".$this->newLine;
              $record .= $this->space."<database>table_warpit_webcati_base</database>".$this->newLine;
              $record .= $this->space."<table>_capi_interviewer_visits</table>".$this->newLine;
              $record .= $this->space."<fields>".$this->newLine;
                foreach ($zad as $key=>$val) { $record .= $this->space.$this->space."<".$key.">".$val."</".$key.">".$this->newLine;  $list[] = $key; }
              $record .= $this->space."</fields>".$this->newLine;
              $record .= $this->space."<listFields>".implode(",",$list)."</listFields>".$this->newLine;
            $record .= "</record>".$this->newLine;
          }


          /* -------------------------------------------------------------
             ----             PROJECTS								                ----
             -------------------------------------------------------------*/

          $tb = DB_WARPIT_WEBCATI_BASE.".".$projectName."_structure";

          $sql = "SELECT * FROM " . $tb .  "
                WHERE  user_id = ".$id_user." AND ( flag_cli IS NULL OR flag_cli != 1 ) ";

          try
          {
            $res = $this->db->SQLexecute($sql);

          }
          catch (\Exception $e)
          {
              $this->clientStatus->reportMissingTable(array('table' => $tb, 'projectName' => $projectName));
              //TODO  Tole je treba rešiti drugače
              $this->actionData->addXml($record);
              return;
              //return $record;
          }

          $this->uploadUpdateDefine[$tb] = array();

          while ($zad_record = $this->db->fetchAssoc($res)) {

          $this->addRecord(array('table' => $tb, 'id_record' => $zad_record['id'], 'project_name' => $projectName));

          $list = array();

            $this->uploadUpdateDefine[$tb][] = $zad_record['id'];

            $record .= "<record>".$this->newLine;
              $record .= $this->space."<database>table_warpit_webcati_base</database>".$this->newLine;
              $record .= $this->space."<table>".$projectName."_structure</table>".$this->newLine;
              $record .= $this->space."<id_project>".$currentProject."</id_project>".$this->newLine;

              $record .= $this->space."<fields>".$this->newLine;
                foreach ($zad_record as $key=>$val) {
                  if (is_null($val) && $key != "id_clien") continue;
                  $record .= $this->space.$this->space."<".$key.">".htmlspecialchars($val)."</".$key.">".$this->newLine;
                  $list[] = $key;
                }
              $record .= $this->space."</fields>".$this->newLine;
              $record .= $this->space."<listFields>".implode(",",$list)."</listFields>".$this->newLine;
            $record .= "</record>".$this->newLine;


          }
        }

        /* -------------------------------------------------------------
           ----             SPECIAL DATA FROM CLIENT                ----
           -------------------------------------------------------------*/


        // Preparing all informations for liveupdate Monitor
        $record .= "<updateMonitor>".$this->newLine;

          // time which produces php
          $record .= $this->space."<phpDate>".date("Y-m-d H:i:s")."</phpDate>".$this->newLine;

          // date time produced by mysql
          $sql = "SELECT NOW() as sqlDate";
          $res = $this->db->SQLexecute($sql);
          $zad = $this->db->fetchAssoc($res);
          $record .= $this->space."<sqlDate>".$zad['sqlDate']."</sqlDate>".$this->newLine;

          // user which is doing live update
          $record .= $this->space."<user_id>".$id_user."</user_id>".$this->newLine;


          $record .= $this->space."<browser><![CDATA[".$_SERVER['HTTP_USER_AGENT']."]]></browser>".$this->newLine;

          // Versions on capi station
          $record .= $this->space."<versions>".$this->newLine;
            $record .= $this->space.$this->space."<start>".$this->versions->startVersion()."</start>".$this->newLine;
            $record .= $this->space.$this->space."<stop>".$this->versions->endVersion()."</stop>".$this->newLine;
            if ($this->versions->done()) $record .= $this->space.$this->space."<upgrades>".implode(",",$this->versions->done())."</upgrades>".$this->newLine;

          $record .= $this->space."</versions>".$this->newLine;



          if ($currentProject) {
            $record .= $this->space."<project>".$this->newLine;
            $record .= $this->space.$this->space."<id>".$currentProject."</id>".$this->newLine;
            $record .= $this->space.$this->space."<name>".$projectName."</name>".$this->newLine;


            $sql = "ANALYZE LOCAL TABLE ".DB_WARPIT_WEBCATI_BASE.".".$projectName."_structure";
            $res = $this->db->SQLexecute($sql);
            $zad = $this->db->fetchAssoc($res);
            $record .= $this->space.$this->space."<tableCheck>".$this->newLine;
              foreach ($zad as $key=>$val)
              $record .= $this->space.$this->space.$this->space."<".$key.">".$val."</".$key.">".$this->newLine;

            $record .= $this->space.$this->space."</tableCheck>".$this->newLine;

            $record .= $this->space.$this->space."<uploadNumberRecords>".count($this->uploadUpdateDefine[$tb])."</uploadNumberRecords>".$this->newLine;
            $record .= $this->space.$this->space."<uploadIdRecords>".implode(",",$this->uploadUpdateDefine[$tb])."</uploadIdRecords>".$this->newLine;


            $sql = "SELECT count(*) as n, status FROM ".DB_WARPIT_WEBCATI_BASE.".".$projectName."_structure
                  WHERE user_id = ".$id_user." GROUP BY status";
            $res = $this->db->SQLexecute($sql);
            while ($zad = $this->db->fetchAssoc($res)) {
              if (is_null($zad['status'])) $zad['status'] = 0;
              $record .= $this->space.$this->space."<statusesUser>".$this->newLine;
                $record .= $this->space.$this->space.$this->space."<status>".$zad['status']."</status>".$this->newLine;
                $record .= $this->space.$this->space.$this->space."<count>".$zad['n']."</count>".$this->newLine;
              $record .= $this->space.$this->space."</statusesUser>".$this->newLine;
            }

            // We make statistics about other users which could made also interviews on this computer.
            $sql = "SELECT count(*) as n, status, flag_cli, user_id FROM ".DB_WARPIT_WEBCATI_BASE.".".$projectName."_structure
                  WHERE user_id != ".$id_user." GROUP BY status, flag_cli, user_id";
            $res = $this->db->SQLexecute($sql);
            while ($zad = $this->db->fetchAssoc($res)) {
              $record .= $this->space.$this->space."<statusesOtherUser>".$this->newLine;
                if (is_null($zad['status'])) $zad['status'] = 0;
                if (is_null($zad['flag_cli'])) $zad['flag_cli'] = 0;
                $record .= $this->space.$this->space.$this->space."<user_id>".$zad['user_id']."</user_id>".$this->newLine;
                $record .= $this->space.$this->space.$this->space."<status>".$zad['status']."</status>".$this->newLine;
                $record .= $this->space.$this->space.$this->space."<flag_cli>".$zad['flag_cli']."</flag_cli>".$this->newLine;
                $record .= $this->space.$this->space.$this->space."<count>".$zad['n']."</count>".$this->newLine;
              $record .= $this->space.$this->space."</statusesOtherUser>".$this->newLine;
            }
            $record .= $this->space."</project>".$this->newLine;
          }
        $record .= "</updateMonitor>";

        foreach($this->recordsData as $table => $recDat)
        {
            $ids = array_column($recDat, 'id_record');

            $data = array('recordsCnt' => count($recDat));
            $this->actionData->addRecordsForUpload($table, $ids);


            if($this->isProject($table))
              $this->clientStatus->dataExists($data);
            else
              $this->clientStatus->dataAboutVisits($data);

        }
        $this->actionData->addXml($record);
  //      $this->actionData->saveXmlToFile(config('localContainer') . 'tanis.txt');
    }

    public function addRecord($data)
    {
      $this->clientStatus->addRecord($data);
      $this->recordsData[$data['table']][] = $data;
    }

    protected function isProject($tableName)
    {
        return $tableName != DB_WARPIT_WEBCATI_BASE . "._Capi_interviewer_visits";
    }
}
