<?php
require_once(__DIR__."/../apl_config.php");
require_once(__DIR__."/../apl_ver.php");
require_once(__DIR__."/../apl_settings.php");
require_once(__DIR__."/login_check.php");


$page_title="Edit Installation";
$page_message="Edit software installation. Update installation information and click the 'Submit' button. For security reasons, only installation IP address and status can be modified.";
$page_message_class="alert alert-info";
$page_header_file_no_data="installations_view.php";


$action_success=0; //will be changed to 1 later only if everything OK
$error_detected=0; //will be changed to 1 later if error occurs
$error_details=null; //will be filled with errors (if any)
$added_records=0;
$updated_records=0;
$removed_records=0;


if (!empty($_GET) && is_array($_GET) && array_walk($_GET, "sanitizeSubmittedData", array("script_filename"=>$script_filename, "html_fields"=>$FORM_FIELDS_WITH_TAGS))) //sanitize super variable with all GET values
    {
    extract($_GET, EXTR_SKIP); //extract sanitized data (don't overwrite existing variables)
    }


if (!empty($_POST) && is_array($_POST) && array_walk($_POST, "sanitizeSubmittedData", array("script_filename"=>$script_filename, "html_fields"=>$FORM_FIELDS_WITH_TAGS))) //sanitize super variable with all POST values
    {
    extract($_POST, EXTR_SKIP); //extract sanitized data (don't overwrite existing variables)
    }


if (empty($installation_id) || !filter_var($installation_id, FILTER_VALIDATE_INT) || empty($rows_array=fetchRow("SELECT * FROM apl_installations WHERE installation_id=?", array($installation_id), array("i")))) //invalid record
    {
    header("Location: $page_header_file_no_data");
    exit();
    }


if (!isset($submit_ok)) //extract fetched variables only if form wasn't submitted (otherwise data entered by user will be overwritten with data from database in case of form submission failure)
    {
    foreach ($rows_array as $row)
        {
        extract($row);
        }
    }


if (isset($submit_ok)) //code between {} tags is identical in files with the same name in /apl_admin and /apl_api directories, EXCEPT header("Location: $page_header_file_no_data"); LINE
    {
    if (!empty($delete_record) && $delete_record==1)
        {
        $removed_records=deleteRow("DELETE FROM apl_installations WHERE installation_id=?", array($installation_id), array("i"));
        if ($removed_records>0)
            {
            $page_message="Deleted $removed_records installation(s) from the database.";
            createReport(strip_tags($page_message), $logged_admin_id, 1, $error_detected);
            header("Location: $page_header_file_no_data");
            exit();
            }
        else
            {
            $error_detected=1;
            $error_details.="Invalid record or database error.<br>";
            }
        }

    if (filter_var($installation_ip, FILTER_VALIDATE_IP) && validateNumberOrRange($installation_status, 0, 2))
        {
        if ($error_detected!=1)
            {
            $updated_records=updateRow("UPDATE apl_installations SET installation_ip=?, installation_status=? WHERE installation_id=?", array($installation_ip, $installation_status, $installation_id), array("s", "i", "i"));
            if ($updated_records<1)
                {
                $error_detected=1;
                $error_details.="Invalid record details or duplicated record (no new data).<br>";
                }
            else
                {
                $action_success=1;

                $rows_array=fetchRow("SELECT * FROM apl_installations LEFT JOIN apl_products ON apl_installations.product_id=apl_products.product_id WHERE apl_installations.installation_id=?", array($installation_id), array("i")); //fetch product details to be used in reports
                foreach ($rows_array as $row)
                    {
                    extract($row);
                    }
                }
            }
        }
    else
        {
        $error_detected=1;
        $error_details.="Invalid IP address or status.<br>";
        }

    if ($action_success==1) //everything OK
        {
        $page_message="$product_title installation on $installation_domain ($installation_ip) updated.";
        createReport(strip_tags($page_message), $logged_admin_id, 1, $error_detected);
        $page_message_class="alert alert-success";
        }
    else //display error message
        {
        $page_message="The database could not be updated because of this error: <br><br>$error_details";
        $page_message_class="alert alert-danger";
        }
    }


$products_array=returnProductsDropdownDisabledArray($product_id);
$clients_array=returnClientsDropdownDisabledArray($client_id);


//Twig templating starts
if (!isset($script_filename)) {$script_filename=basename($_SERVER['SCRIPT_FILENAME']);} //if $script_filename is not set yet (usually set in login_check.php), get it now (will be used in Twig forms)

Twig_Autoloader::register();
$loader=new Twig_Loader_Filesystem("../apl_templates"); //load files from templates directory
$twig=new Twig_Environment($loader); //create Twig environment

$twig->addExtension(new \nochso\HtmlCompressTwig\Extension());

echo $twig->render(basename(__DIR__)."/".basename(__FILE__, ".php").".twig", get_defined_vars()); //render requested template
//Twig templating ends