<?php

    ini_set("log_errors", 1);
    ini_set("error_log", "./php-error.log");

    writeToLog($_REQUEST, 'incoming'); //comment it when everything will be debugged

    //=== CONSTANTS zone
    //
    //The system name of custome field 'Run After-sale'
    define("UFRAS", "UF_CRM_1614846790"); //UF_CRM_1614846790

    //=== VALIDATION & INITIALIZATION zone
    //Validates Webhook params and fill variables by Webhook params
    
    require __DIR__ . '/vendor/autoload.php';
    
    use \App\Bitrix24\Bitrix24API;
    
    $webhookURL = 'https://crm.max2.eu/rest/3/rhwjojnpeksrvqrv/';
    
    $bx24 = new Bitrix24API($webhookURL);

    $InvoiceID = $_REQUEST['data']['FIELDS']['ID'];
    // file_put_contents(getcwd() . '/hook.log', "\n\$InvoiceID " . $InvoiceID, FILE_APPEND);
    
    //Get Invoice fields. 
    $InvoiceFields = $bx24->getInvoice($InvoiceID);
    $Company = $InvoiceFields['UF_COMPANY_ID'];
    if (!$Company) exit; //If no Company in Invoicee, exit.
    //Take 'Run After Sale' number right from Company's table
    $CompanyFields = $bx24->getCompany($Company);
    
    $CompanyRAS = explode("-", $CompanyFields[UFRAS][0]);
    //Now $CompanyRAS[0] is a string with the Year and $CompanyRAS[1] is 
    //custom field name 'Run After-sale' in Company table
    //It should be YYYY-R format. Where YYYY is year and R is 'Run After-sale' option
    ////Run After-sale might be 0 - TBD, 1 - yes, call, 2 - yes, Email,
    //4 - not in this year.

    $RunAfterSaleYear = $CompanyRAS[0];
    $RunAfterSale = $CompanyRAS[1];
    
    //Which year is today?
    $CurrentYear = date("Y");
    //If current year is greater then Company's
    if (intval($CurrentYear) > intval($RunAfterSaleYear)) {
        //Change Company RAS Year to current year
        $CompanyRAS[0] = $CurrentYear;
        $CompanyRAS[1] = "0"; //and change RAS to zero which is TBD
        $RASString = $CompanyRAS[0] . "-" . $CompanyRAS[1];
        try {
            $bx24->updateCompany($Company, [UFRAS => $RASString], ["REGISTER_SONET_EVENT" => "Y"]);
            } catch (Exception $e) {
                $projectId = 'Tam bil error ' . $e;
                file_put_contents(getcwd() . '/hook.log', "\nError " . $projectId, FILE_APPEND);
            }
    }
    
    $HappyThisYearString = $CurrentYear . '-01-01';
    $HappyThisYearTime = strtotime($HappyThisYearString);
        
    
    //=== WORKING ZONE
    
    //Summarize only this company's Invoice Amounts
    //First, let's get filtered invoices into an array
    $getInvoiceListGeneratorObject = $bx24->getInvoiceList(['ID' => 'ASC'],
    ['UF_COMPANY_ID' => $Company, 'PAYED' => 'Y'],
    ['ID', 'PRICE', 'DATE_PAYED', 'UF_DEAL_ID'],);
    //Invoice amounts into Array
    $InvoiceArray = array();
    foreach ($getInvoiceListGeneratorObject as $value) {
        $InvoiceArray = array_merge($InvoiceArray, $value);
    }

    //Summarize Invoice Amounts
    $m = count($InvoiceArray);
    if ($m == 0) {
        file_put_contents(getcwd() . '/hook.log', "\$no payments from this customer at all\n", FILE_APPEND);
    exit(json_encode(array('error' => 'no payments from this customer at all' )));
    }
    $RevenueCurrentYear = 0;
    for ($i = 0; $i < $m; $i++) {
        $t = strtotime($InvoiceArray[$i]['DATE_PAYED']);
        if ($t >= $HappyThisYearTime) {
        $RevenueCurrentYear += $InvoiceArray[$i]['PRICE'];
        }
    }
    if ($RevenueCurrentYear == 0) {
        file_put_contents(getcwd() . '/hook.log', "\n\$no payments from this customer this year\n", FILE_APPEND);
        exit(json_encode(array('error' => 'no payments from this customer this year' )));
    }

    //In irder to know custom list IDs, uncomment and run the following piece of script
    /* try {
    $Lists = $bx24->request('lists.get', [
        'IBLOCK_TYPE_ID' => 'lists']);
    } catch (Exception $e) {
        $projectId = 'Tam bil error ' . $e;
    }
    file_put_contents(getcwd() . '/hook.log', "\$Lists   " . print_r($Lists, true), FILE_APPEND); */
    
    //Which is IBLOCK_ID? 17!
    $Elements = $bx24->request('lists.element.get', ['IBLOCK_TYPE_ID' => 'lists', 'IBLOCK_ID' => 17]);
    
    //What is "Small Deal Amount"?
    //Reading 1st (0's) element of the list "Custom Parameters"
    $SmallDealAmount = intval($bx24->request('lists.element.get', ['IBLOCK_TYPE_ID' => 'lists',
    'IBLOCK_ID' => 17]) [0]['PROPERTY_76'][153]);
    
    //Is $RevenueCurrentYear greater, then "Small Deal Amount"?
    if ($RevenueCurrentYear < $SmallDealAmount) {
        $RunAfterSale = 2; //Call
    } else {
        $RunAfterSale = 1; //Email
    }
    
    //In order to know custom field name, uncomment and run the following script
    // $CompanyFields = $bx24->getCompany($Company);
    // file_put_contents(getcwd() . '/hook.log', "\$CompanyFields \n" . print_r($CompanyFields, true), FILE_APPEND);
    //The same with Deals
    //$DealFields = $bx24->getDealFields();
    //file_put_contents(getcwd() . '/hook.log', "\$DealFields \n" . print_r($DealFields, true), FILE_APPEND);
    
    //Let's write $RunAfterSale into the Company table!!!
    //While implementing, don't forget to change 'UF_CRM_...'
    $RunAfterSale = $CurrentYear . "-" . $RunAfterSale;
    $bx24->updateCompany($Company, [UFRAS => $RunAfterSale], ["REGISTER_SONET_EVENT" => "Y"]);
    
    //In order to know current CRM statuses, place fake deals into interesting stages and read stage ID
    $DealArray = $bx24->getDeal(118);
    // file_put_contents(getcwd() . '/hook.log', "\$DealArray" . print_r($DealArray, true), FILE_APPEND);
    
    
    $CompanyFields = $bx24->getCompany($Company);
    $DealTitle = 'AS: ' . $CompanyFields['TITLE'];
    
    //Don't try to copy that Deal into the 'After sale' pipeline! https://dev.1c-bitrix.ru/rest_help/crm/cdeals/crm_deal_fields.php
    //CREATE the after-sale Deal with "AS:" prefix
    $bx24->addDeal(
        ['TITLE' => $DealTitle,
        'TYPE_ID' => 'SALE',
        'STAGE_ID' => 'C1:NEW', //This one take from $DealArray = $bx24->getDeal(118);
        'CURRENCY_ID' => 'EUR',
        'COMPANY_ID' => $CompanyFields['ID'],
        'OPENED' => 'Y',
        'CLOSED' => 'N',
        'IS_RETURN_CUSTOMER' => 'Y',
        'COMMENTS' => 'The Deal created automatically for After-sale 
        purposes using SumCustomerPaymentsThisYear.php Webhook run by Invoice ID = ' . $InvoiceID,
        'CATEGORY_ID' => 5], //This one take from $DealArray = $bx24->getDeal(118);
        ["params" => ["REGISTER_SONET_EVENT" => "Y"]]);
    //
    //BUT PLEASE don't forget to remove the tonnel between the Aberchung (accounting) Pipeline and
    //the Aftersale Pipeline. Because we'll organize such tonnel right in current script further on!
    // 
    
    //$bx24->updateDeal($DealId, ['UF_CRM_1614486115944' => $n], ['']);

    //=== FUNCTIONS zone
    function writeToLog($data, $title = '') {
            $log = "\n------ max2SumInvoices.php ------------------\n";
            $log .= date("Y.m.d G:i:s") . "\n";
            $log .= (strlen($title) > 0 ? $title : 'DEBUG') . "\n";
            $log .= print_r($data, 1);
            file_put_contents(getcwd() . '/hook.log', $log, FILE_APPEND);
            return true;
    }