<?php
if (!class_exists('Database')) require_once("common_cadline_libraries/crm_database.class.php");

$fileName   = isset($_POST['file']) ? $_POST['file'] : '';
$jsonFile   = isset($_POST['jsonFile']) ? $_POST['jsonFile'] : '';
$htmlUrl    = isset($_POST['htmlUrl']) ? $_POST['htmlUrl'] : '';
$published  = isset($_POST['published']) ? $_POST['published'] : false;
$published  = $published == 'true' ? 1 : 0;

$zip = new ZipArchive();
$zip->open('datas/' . $fileName);
$xmlFile = $zip->getFromName('details.xml');

$xml        = new SimpleXMLElement($xmlFile);
$element    = $xml->xpath("//Item[@Name='{$jsonFile}']")[0];

$query = "SELECT * FROM `cl_hlusers`.`zendesk_api` WHERE fileName = ? AND published = ?";
Database::getInstance()->query($query, array('si', $jsonFile, $published));
$res = Database::getInstance()->fetchNext();

if (empty($res)) {
    $zendesk = array(
        'fileName'  => $jsonFile,
        'crc'       => $element['Crc'][0],
        'url'       => $htmlUrl,
        'published' => $published
    );
    Database::getInstance()->insert(CRMADATBAZIS . ".zendesk_api", $zendesk, 'sisi');
} else {
    Database::getInstance()->update(
        CRMADATBAZIS . ".zendesk_api",
        array(
            'crc'       => $element['Crc'][0]
        ),
        array('id'  => $res['id']),
        'si'
    );
}

echo json_encode('Updated');

$zip->close();
