<?php

/*
 * ZENDESK - OPPORTUNITY STAGE
 * IMPORT OPPORTUNITY STAGE LIST FROM SALESFORCE
 * Will take the top stage for dupplicate entries
 */
 
// Utility functions
require_once("../shared/functions.php");

// Zendesk Connect
require("config.Zendesk.inc.php");

// Zendesk Class
require("Zendesk.class.php");

if(isset($_POST['batchUpdate'])) { $batchUpdate = $_POST['batchUpdate']; }
else $batchUpdate = 1;

if(isset($_POST['organizationid']) && $_POST['organizationid'] > 0) { $organizationid = $_POST['organizationid']; }
else $organizationid = 0;

if(isset($_GET['debug']) && $_GET['debug'] > 0) { $debug = $_GET['debug']; }
else $debug = 0;

// Init vars & arrays & objets
$allSFIDs = array();
$allZIDs = array();
$allViews = array();
$AllOrganizations = array();
$UpdateOrganization = array();
$updated = $error = $ignored = 0;
// Set old category tags to purge
$oldTags = array('prod', 'live', 'new', 'test');
// Start Zendesk Class
$Zendesk = new Zendesk($resource, $token, $username);

if(isset($_POST['action']) && $_POST['action'] == 'upload' && isset($_FILES) && $_FILES['inputfile']['error'] == 0) {

    /*
     * 1 - OPEN SALESFORCE OPPORTUNITIES
     */

    // Store uploaded priority List
    $dir = "./cache";
    $uploadedFileNameArr = explode(".", $_FILES['inputfile']['name']);
    $ext = end($uploadedFileNameArr);
    move_uploaded_file($_FILES['inputfile']['tmp_name'], "$dir/stage.$ext" ); //Move the file to desired directory.
    $file = "$dir/stage.$ext";

    // Process file
    if (($handle = fopen($file, "r")) !== FALSE) {

        $row = 1;
        while (($dataRaw = fgetcsv($handle, 1000, ",")) !== FALSE) {
            if($row > 1) { //  && $row < 10

                $data = new stdClass();

                $data->Stage                    = $dataRaw[0];
                $data->OpportunityID            = $dataRaw[1];
                $data->OpportunityName          = $dataRaw[2];
                $data->OpportunityOwner         = $dataRaw[3];
                $data->ParentAccountID          = $dataRaw[4];
                $data->ParentAccountName        = $dataRaw[5];
                $data->AccountID                = $dataRaw[6];
                $data->AccountName              = $dataRaw[7];

                if($data->ParentAccountID) { // Is Parent
                    $SFID = $SFID_original = $data->ParentAccountID;
                    $name = $data->ParentAccountName;
                }
                else { // Is Child
                    $SFID = $SFID_original = $data->AccountID;
                    $name = $data->AccountName;
                }

                $SFID = 'SFACCOUNT'.md5($SFID); // generate hash to manage upper/lower case duplicates

                $stage = $Zendesk->MatchStage($data->Stage);

                if(isset($AllOrganizations[$SFID]) && isset($AllOrganizations[$SFID]->stage) && $AllOrganizations[$SFID]->stage->level >= $stage->level) {
                    /*
                     * Ignore existing accounts or the previous lower opportunities
                     */
                }
                else {
                    /*
                     * New Line to read
                     */
                    $AllOrganizations[$SFID]                    = new stdClass();
                    $AllOrganizations[$SFID]->name              = $name;
                    $AllOrganizations[$SFID]->opportunityID     = $data->OpportunityID;
                    $AllOrganizations[$SFID]->opportunity       = $data->OpportunityName;
                    $AllOrganizations[$SFID]->SFID              = $SFID_original;
                    $AllOrganizations[$SFID]->stage             = $stage; // Set stage->level in stage->zendesk
                    $AllOrganizations[$SFID]->stage->name       = $data->Stage;

                    $allSFIDs[] = $SFID;
                }
            }
            $row++;
        }
        fclose($handle);
    }

    /*
     * 2 - LIST ALREADY SYNCHED ORGANIZATIONS
     */

    if($debug) { krumo($AllOrganizations); }
    if(count($AllOrganizations)) {

        /*
        * ORGANISE JSON DATA
        */

        $PutOrganization = new stdClass();
        if($batchUpdate) { $PutOrganization->organizations = array(); }

        /*
        * PREPARE CHUNKS OF 100
        */

        $AllQueries = array_chunk($allSFIDs, 40, true);

        /*
        * POST TO ZENDESK JSON DATA
        */

        $i=0;
        foreach($AllQueries as $Query) {

            $options = array(
                    CURLOPT_URL => $resource."organizations/show_many.json?external_ids=".implode(',', $Query),
                    CURLOPT_USERPWD => $username."/token:$token",
                    CURLOPT_RETURNTRANSFER =>true,
                    CURLOPT_ENCODING => "",
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => "GET",
            );
            require("curl.Zendesk.inc.php");
            $result = json_decode($result);

            if($result->count) {
                foreach($result->organizations as $organization) {
                    $ZID    = $organization->id;
                    $SFID   = $organization->external_id;
                    if($SFID && isset($AllOrganizations[$SFID])) {
                        if($organization->organization_fields->production != $AllOrganizations[$SFID]->stage->zendesk ||!array_search($AllOrganizations[$SFID]->stage->zendesk, $organization->tags)) {
                            
                            // Prepare Update
                            if($batchUpdate) {

                                /*
                                * Case Batch (chunks)
                                */

                                // Default Param
                                $PutOrganization->organizations[$i] = new stdClass();
                                $PutOrganization->organizations[$i]->id = (int) $ZID;
            
                                // Tags
                                $newTags = array($AllOrganizations[$SFID]->stage->zendesk);

                                // Remove old category tags
                                $Zendesk->RemoveOrganizationTag($PutOrganization->organizations[$i]->id, $oldTags);
            
                                // Add new category and TAM tags
                                $Zendesk->AddOrganizationTag($PutOrganization->organizations[$i]->id, $newTags);
                
                                // Stage
                                $PutOrganization->organizations[$i]->organization_fields = new stdClass();
                                $PutOrganization->organizations[$i]->organization_fields->production = $AllOrganizations[$SFID]->stage->zendesk;
            
                                // Store ID
                                $allZIDs[] = $ZID;
                            }
                            else {

                                /*
                                * Case individual organization update (for debug)
                                */

                                // Default Param
                                $PutOrganization->organization = new stdClass();
                                $PutOrganization->organization->id = (int) $ZID;

                                // Tags
                                $newTags = array($AllOrganizations[$SFID]->stage->zendesk);

                                // Remove old category tags
                                $Zendesk->RemoveOrganizationTag($PutOrganization->organization->id, $oldTags);

                                // Add new category and TAM tags
                                $Zendesk->AddOrganizationTag($PutOrganization->organization->id, $newTags);

                                // Category
                                $PutOrganization->organization->organization_fields = new stdClass();
                                $PutOrganization->organization->organization_fields->vip_merchant = 'cat'.$priority;

                                // Stage
                                $PutOrganization->organization->organization_fields = new stdClass();
                                $PutOrganization->organization->organization_fields->production = $AllOrganizations[$SFID]->stage->zendesk;
                

                                $queryParameters = $PutOrganization;
                                $options = array(
                                        CURLOPT_URL => $resource."organizations/$ZID.json",
                                        CURLOPT_USERPWD => $username."/token:$token",
                                        CURLOPT_RETURNTRANSFER =>true,
                                        CURLOPT_ENCODING => "",
                                        CURLOPT_MAXREDIRS => 10,
                                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                                        CURLOPT_CUSTOMREQUEST => "PUT",
                                        CURLOPT_POSTFIELDS => json_encode($queryParameters),
                                        CURLOPT_HTTPHEADER => array('Content-Type: application/json', 'Content-Length: ' . strlen(json_encode($queryParameters)))
                                );
                                require("curl.Zendesk.inc.php");
                            
                                $result = json_decode($result);
                                $display_result = json_encode($PutOrganization) . "\n<br/>" . $result;

                            }

                            $i++;

                            $updated++;
                        }

                    }
                }
            }
        }


        if($debug) { krumo($PutOrganization); }
        if(isset($PutOrganization) && isset($PutOrganization->organizations) && count($PutOrganization->organizations) && $batchUpdate) {

            /*
            * PREPARE CHUNKS OF 100
            */

            $AllQueries = array_chunk($PutOrganization->organizations, 100, true);

            /*
            * POST TO ZENDESK JSON DATA
            */

            foreach($AllQueries as $Query) {

                $PutOrganization = new stdClass();
                $PutOrganization->organizations = $Query;

                $queryParameters = $PutOrganization;
                $options = array(
                        CURLOPT_URL => $resource."organizations/update_many.json", //?ids=".implode(',', $allZIDs),
                        CURLOPT_USERPWD => $username."/token:$token",
                        CURLOPT_RETURNTRANSFER =>true,
                        CURLOPT_ENCODING => "",
                        CURLOPT_MAXREDIRS => 10,
                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                        CURLOPT_CUSTOMREQUEST => "PUT",
                        CURLOPT_POSTFIELDS => json_encode($queryParameters),
                        CURLOPT_HTTPHEADER => array('Content-Type: application/json', 'Content-Length: ' . strlen(json_encode($queryParameters)))
                );
                require("curl.Zendesk.inc.php");

                //$result = json_decode($result);
                $display_result = "Job created to update $updated organizations... <br /><br /><b>Do not forget to <a id='Populate' href='javascript:void(0)'>populate to existing tickets</a></b> if needed. <div class='loader'></div><br /><br />Job result = <small>$result</small>";
            }

            //$result = json_decode($result);
        } else { $display_result = "No Organization to update."; }
    }
    else { $display_result = "No Organization found."; }


}

?>
<html lang="en">
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8">
        <meta charset="utf-8">
        <title>Account Priority | Zendesk Import</title>
        <link rel="icon" type="image/png" href="images/podium.png" />

        <script src="//code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
        <script src="//code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />

        <!-- Bootstrap CSS -->
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

        <!-- Bootstrap and Popper JS -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" crossorigin="anonymous"></script>
        <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

        <style>
            .ui-autocomplete {
                z-index: 100;
            }
            .loader {
                display: none;
                border: 5px solid #f3f3f3;
                -webkit-animation: spin 1s linear infinite;
                animation: spin 1s linear infinite;
                border-top: 5px solid #555;
                border-radius: 50%;
                width: 50px;
                height: 50px;
            }

            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
        </style>

        <script>
            $(function() {
                $('[data-toggle="tooltip"]').tooltip();

                $( 'button.submit' ).click(function() {
                    $(this).parent().parent().submit();
                });

                $( '#Populate').click(function(){
                    $.ajax({
                        type: "GET",
                        url: 'Zendesk_PopulateTags.ajax.php',
                        beforeSend: function() {
                            $(".loader").show();
                        },
                        success: function(data) {
                            if(data == "OK") {
                                console.log("Populatin OK");
                                $(".loader").replaceWith("<div>OK</div>");
                            }
                            else {
                                console.log("Populating Error");
                                $(".loader").replaceWith("<div>Error</div>");
                            }
                        }
                    });
                });
            });
        </script>

    </head>
    <body>

         <div class="container">
         <?php if(isset($display_result)) { ?>
            <div class="alert alert-warning" role="alert"><?=$display_result?></div>
         <?php } ?>

            <h2>Upload a Salesforce Opportunity Stage Extract</h2>
            <div class="well well-sm" style="width:620px;">To start a Zendesk synchronization, you need to download a <b>CSV</b> extract with <b>UTF-8</b> encoding of the Salesforce report <b><a href="https://hipay.lightning.force.com/one/one.app#/sObject/00O0Y000007LuqpUAC/view" target="_blank"></a>Accounts ID by Priority Note</b>.</div>
            <div class="row">
            <form method="post" action="" enctype="multipart/form-data" class="form-inline">
                
                <div class="row" style="padding:5px 0px 25px 15px">
                        <b>Update mode:</b>
                        <label for ="batchUpdate1" class="radio-inline"><input type="radio" id="batchUpdate1" name="batchUpdate" value="1" checked="checked" /> Batch</label>
                        <label for ="batchUpdate0" class="radio-inline"><input type="radio" id="batchUpdate0" name="batchUpdate" value="0" /> Invidual <i>(for debug only)</i></label>
                </div>

                <div class="form-group">
                    <label for="inputfile">Your local file</label>
                    <input type="file" id="inputfile" name="inputfile" class="form-control" accept=".csv" />
                </div>
                <div class="form-group">
                    <input type="hidden" name="action" value="upload" />
                    <button type="button" class="btn btn-info submit"><span class="glyphicon glyphicon-open"></span> Upload</button>
                </div>
            </form>
            </div>
        </div>
        
    </body>
</html>