<?php

if(!isset($_GET['type'])) die("error_missing_type");
include("check_session.php");
include("db_connection.php");


require_once 'vendor/autoload.php';


?>

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
    <title>Zelos - Designer</title>
    <style>
        html, body {
            font-family: sans-serif;
        }
    </style>

    <?php
    /** https://www.stimulsoft.com/en/documentation/online/programming-manual/index.html?reports_and_dashboards_for_php_web_designer_deployment.htm */
    $js = new \Stimulsoft\StiJavaScript(\Stimulsoft\StiComponentType::Designer);
    $js->renderHtml();
    ?>
    <script src="js/jquery-1.12.4.js"></script>
    <script type="text/javascript">

        <?php
        $handler = new \Stimulsoft\StiHandler();
        $handler->license->setKey('6vJhGtLLLz2GNviWmUTrhSqnOItdDwjBylQzQcAOiHl2rCPWxELIofkY3UYnx7oY+1oDDHrnFg9gbvUjuP8P0f0OWJOyrrUu/OMaviDWSUxpASfBHo6Tz55h05Be2CGchFnf3jE/IpBhZ24RxugUwXpjUK9N6h3SAz29+5Gvq/Uv95dW+jQ4y+agQHDKSZfHXgvnjPX5cI9vbx5TPhTXIk2vAuy5ksH1CzU5UK8MDFw1+YK2SNFzg6t/FmQZ5ktupZtEA7vK1yneS1I8MyLj4Y8ngnhhAvuUzxuN74DLl88amxUK9G0oHKLayKwnkmTaIN8zUyugaqPbUd8EL+898FgajMQFJWjBfCh7sLU6ciDDPr46/XiXjb8N7MMVveM4sfTrQ5K+mY1w0Q5TiYjqm0v/RaMarVS9rvF5ma5coFtWt/r0SgvdmOmtEfMjhWFJ/XGC3hYS8dzGSBh7CIuWyn/mzGC3q/BfrEajJFSl2MR8I63fFIT05VP5tPwpB+8R0OSKrdm49GixTkiW8JSB0pyAeradYSGx35uWKjv5/Ye9efaa32ohX4uCIRAQ5hgk7HvAPbioi/IjJGWdGrcJ1A==');
        //$handler->license->setFile('license.key');
        $handler->renderHtml();

        /** https://www.stimulsoft.com/en/documentation/online/programming-manual/index.html?reports_and_dashboards_for_php_web_designer_settings.htm */
        $options = new \Stimulsoft\Designer\StiDesignerOptions();
        $options->appearance->fullScreenMode = true;

        /** https://www.stimulsoft.com/en/documentation/online/programming-manual/index.html?reports_and_dashboards_for_php_web_designer_deployment.htm */
        $designer = new \Stimulsoft\Designer\StiDesigner($options);
        //$options->localization = 'it.xml';

        /** https://www.stimulsoft.com/en/documentation/online/programming-manual/index.html?reports_and_dashboards_for_php_engine_connecting_sql_data.htm */
        $designer->onBeginProcessData = true;


        /** https://www.stimulsoft.com/en/documentation/online/programming-manual/index.html?reports_and_dashboards_for_php_web_designer_saving_report.htm */
        $designer->onSaveReport = 'onSaveReport';
        $designer->onSaveAsReport = 'onSaveAsReport';


        /** https://www.stimulsoft.com/en/documentation/online/programming-manual/index.html?reports_and_dashboards_for_php_web_designer_creating_editing_report.htm */
        $report = new \Stimulsoft\Report\StiReport();

        $view_type = isset($_GET['type']) ? $_GET['type'] : '';

        // DOBBIAMO connetterci al db e caricare il project...
        if(!isset($_GET['id_report'])) {

          // SE non abbiamo un ID report, dobbiamo comunque allacciare una source... ma come???
          if($view_type == 'viewstat'){

            // devo creare un sample del project datasource. (in realtà prendiamo quello dal db del project vuoto.)
            $q_empty_project = mysqli_query($db,"SELECT payload FROM ze_report_projects WHERE type='sample_empty'");
            $assoc_empty = mysqli_fetch_assoc($q_empty_project);

            $array=json_decode(json_decode( $assoc_empty['payload']));

            $filters = isset($_GET['view_filters']) ? $_GET['view_filters'] : base64_encode("[]");
           
            $array->Dictionary->Databases->{0}->PathData = "/" . basename(__DIR__) . "/report_json_api.php?view=viewstat&name_view=" . $_GET['name_view'] . "&view_filters=" . $filters;

            //print_r($array->Dictionary);

            $report->load(json_encode($array));

          }

        } else {

          $get_q = mysqli_query($db,"SELECT payload FROM ze_report_projects WHERE id = '".$_GET['id_report']."'");
          $assoc_project = mysqli_fetch_assoc($get_q);
          
          // devo cambiare il pathdata se abbiamo il parametro...
          $array=json_decode(json_decode($assoc_project['payload']));
          //print_r($array);          
       
          $id_ref = isset($_GET['id_ref']) ? $_GET['id_ref'] : 0;
          $id_report = isset($_GET['id_report']) ? $_GET['id_report'] : 0;

          //if($id_ref >= 0){
          
            switch($view_type){

              case 'invoice':
                if($id_ref >= 0)
                  $array->Dictionary->Databases->{0}->PathData = "/" . basename(__DIR__) . "/report_json_api.php?view=invoice&invoice=" . intval($id_ref) . "&id_report=" . $id_report;
                  break;

              case 'quotation':
                if($id_ref >= 0)
                  $array->Dictionary->Databases->{0}->PathData = "/" . basename(__DIR__) . "/report_json_api.php?view=quotation&contracts_data=" . intval($id_ref). "&id_report=" . $id_report;;
                  break;

              case 'contracts':
                if($id_ref >= 0)
                  $array->Dictionary->Databases->{0}->PathData = "/" .  basename(__DIR__) . "/report_json_api.php?view=quotation&contracts_data=" . intval($id_ref). "&id_report=" . $id_report;;
                  break;

              case 'anag_lead': 
                $array->Dictionary->Databases->{0}->PathData = "/" .  basename(__DIR__) . "/report_json_api.php?view=anag_lead&anag_data". "&id_report=" . $id_report;
                break;

              case 'anag_contact':
                $array->Dictionary->Databases->{0}->PathData = "/" .  basename(__DIR__) . "/report_json_api.php?view=anag_contact&anag_data". "&id_report=" . $id_report;
                break;

              case 'anag_customer':
                $array->Dictionary->Databases->{0}->PathData = "/" .  basename(__DIR__) . "/report_json_api.php?view=anag_customer&anag_data". "&id_report=" . $id_report;
                break;

              case 'anag_global':
                $array->Dictionary->Databases->{0}->PathData = "/" .  basename(__DIR__) . "/report_json_api.php?view=anag_global&anag_data". "&id_report=" . $id_report;
                break;

              case 'viewstat':
                $filters = isset($_GET['view_filters']) ? $_GET['view_filters'] : base64_encode("[]");
                $array->Dictionary->Databases->{0}->PathData = "/" . basename(__DIR__) . "/report_json_api.php?view=viewstat"."&id_report=" . $id_report."&name_view=" . $_GET['name_view'] . "&view_filters=" . $filters;
                break;

  

            }

         // }

          $report->load(json_encode($array));

        }


        $report->onBeforeRender = 'onBeforeRender';
        
        $designer->report = $report;
        ?>

        const type_designer = "<?php 

          if(isset($_GET['name_view'])){

            echo isset($_GET['type']) ? $_GET['type'] . "_" . $_GET['name_view'] : 'generic';

          } else {

            echo isset($_GET['type']) ? $_GET['type'] : 'generic' ;

          }
        
        ?>";

        // After loading the HTML page, display the visual part of the Designer in the specified container.
        function onLoad() {
            <?php
            $designer->renderHtml('designerContent');
            ?>
        }

  
        const id_source = "<?php echo isset($_GET['id_report']) ? $_GET['id_report'] : 0 ?>";

        function onSaveReport(args){

          var fileName = args.fileName;
          var report = args.report;

          var jsonReport = args.report.saveToJsonString();
          $.post('report_json_api.php?store_project' , {
            "filename" : fileName, "json" : jsonReport, "type" : type_designer, "id_report" : id_source
          }).done(x=>{


          });

        }

        function onSaveAsReport(args){

          var fileName = args.fileName;
          var report = args.report;
          var jsonReport = args.report.saveToJsonString();

          $.post('report_json_api.php?store_project' , {
            "filename" : fileName, "json" : jsonReport, "type" : type_designer,
            "save_as" : true, "id_report" : id_source
          }).done(x=>{

            if(typeof x === 'object'){

              // deve ritornarci x.
              window.location.reload();

            }

          });

        }

        function onBeforeRender(args){

          console.log(args)

          var report = args.report;
          report.dictionary.synchronize();
          console.log('ho syncato')

        }

    

    </script>
</head>
<body onload="onLoad();">
<div id="designerContent"></div>
</body>
</html>
