<?php
defined($security_key) or exit;

///------------------------------------------
// Application related calls
//------------------------------------------
$action = $request[2] ?? '';

//------------------------------------------
// Check for action & start application API
//------------------------------------------
if ($action !=''){

//------------------------------------------
//Connect to DB
//------------------------------------------
$pdo = dbConnect($dbname);
$pdo2 = dbConnect($dbname);

//------------------------------------------
//CONTENT FROM API (POST)
//------------------------------------------
$post_content = json_decode(decode_payload($input),true);

//SoldTo is empty
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}

//default whereclause
$whereclause = 'WHERE';

switch ($permission) {    
    case '4': 
        $whereclause .= '';
        break;
    case '3':
        $condition = '__salesid___'.$partner->salesid.'___soldto___%';
        $whereclause = ' e.accounthierarchy  like "'.$condition.'" AND ';
        break;
    case '2':
        $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
        $whereclause .= ' e.accounthierarchy like "'.$condition.'" AND ';
        break;
    default:
        $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search.'___shipto___'.substr($partner->shipto, 0, strpos($partner->shipto, "-")).'%___location___'.substr($partner->location, 0, strpos($partner->location, "-")).'%';
        $whereclause .= ' e.accounthierarchy like "'.$condition.'" AND ';
        break;
} 

//------------------------------------------
// Actions
//------------------------------------------
switch ($action) {
    case 'unscribe':
        // -----------------------------------------------------------
        // Unscribe from mailinglist -> set communication status to 0
        // -----------------------------------------------------------   
        if (isset($post_content['email']) && $post_content['email'] !=''){

            $sql = 'UPDATE communication SET status = 0 WHERE email = ?';
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$post_content['email']]);

            if($stmt->execute()){
                $messages = $unscribe_msg1;
            } else{
                $messages = $unscribe_msg_error;
            }

        } else{
            $messages = $unscribe_msg_error;
        }

         //Encrypt results
         $messages = generate_payload($messages);
         //Send results
         echo $messages;

    break;
     
    case 'register':
    // --------------------------------------------
    // User registration
    // --------------------------------------------   
    $firmware_account_send = 0; //Default value -> no mail send
    $communication_check = 0; //Check communication record
    $message_box = [];
    $timestamp = date("Y-m-d H:i:s");

    // Create history description
    $history_description = [
        "start_date"=>$timestamp,
        "end_date"=>date("Y-m-d", strtotime("+730 days")),
        "organization"=>strip_tags(trim($post_content['organization'])),
        "phone"=>strip_tags(trim($post_content['phone'])),
        "city"=>strip_tags(trim($post_content['city'])),
        "country"=>strip_tags(trim($post_content['country'])),
        "email_consent"=>strip_tags(trim($post_content['email_consent'])),
        "terms_consent"=>strip_tags(trim($post_content['terms_consent']))
    ];

    $description = json_encode($history_description, JSON_UNESCAPED_UNICODE);
    // --------------------------------------------
    // Check if multiple serialnumbers are provided
    // --------------------------------------------
    if(is_array($post_content['sn'])){
        foreach ($post_content['sn'] as $sn){
            //Get equipmentid based on rowID
            $rowID = getrowID($dbname,'rowID','equipment','serialnumber="'.$sn.'"');

            if ($rowID){
                //check if under warranty
                $warranty = getrowID($dbname,'rowID','equipment_history','equipmentid="'.$rowID['rowID'].'" && (type="'.$type9.'" || type="'.$type10.'" || type="'.$type11.'" || type="'.$type12.'")');
                if ($warranty){
                // --------------------------------------------
                // Already under contract
                // --------------------------------------------
                //Serialnumber under warranty
                $message_box[] = $sn.' - '.$register_message_2;
                $communication_check = 1;
                } else
                {
                // --------------------------------------------
                // Not under warranty
                // --------------------------------------------
                //Send user firmware account
                $firmware_account_send = 1;
                //create history
                // Prepare queries
                $sql = 'INSERT INTO equipment_history (equipmentid, type, description, created, createdby,updatedby) VALUES (?,?,?,?,?,?)';
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$rowID['rowID'],$type9,$description,$timestamp,$post_content['email'],$post_content['email']]);

                //GET PARTNER DETAILS OF EQUIPMENT
                $partner_equipment = getrowID($dbname,'accounthierarchy','equipment','rowID="'.$rowID['rowID'].'"');
                $partner_equipment = json_decode($partner_equipment['accounthierarchy']);

                //Setup partnerhierarchy (salesID)
                $partnerhierarchy =[
                    "salesid"=>$partner_equipment->salesid,
                    "soldto"=>$partner_equipment->soldto
                ];

                //Setup variables for partner
                $partnername = $post_content['organization'];
                $partnernotes = 'created based on user registration';
                $salesID = json_encode($partnerhierarchy, JSON_UNESCAPED_UNICODE);
                $createdby = 'system';

                //Check if shipto is empty and if empty search partner or create
                if ($partner_equipment->shipto == ''){
                    $partner_shipto = getrowID($dbname,'partnerID','partner','partnername = "'.$partnername.'" && partnertype="'.$partnertype3.'"');
                    if ($partner_shipto){
                        //Partner exists - Use it
                        $partnerhierarchy['shipto'] = $partner_shipto['partnerID'].'-'.$partnername;
                    } else {
                        //Partner does not exist create
                        $sql = 'INSERT INTO partner (partnertype,partnername,salesID,createdby,status) VALUES (?,?,?,?,?)';
                        $stmt = $pdo2->prepare($sql);
                        $stmt->execute([$partnertype3,$partnername,$salesID,$createdby,'1']);

                        //Get rowID of created partner and use it
                        $partner_rowid = $pdo2->lastInsertId();
                        $partnerhierarchy['shipto'] = $partner_rowid.'-'.$partnername;
                    }
                } else {
                    // Shipto exist use it
                    $partnerhierarchy['shipto'] = $partner_equipment->shipto;
                }
                //Check if location is empty and if empty search partner or create
                if ($partner_equipment->location == ''){
                    $partner_location = getrowID($dbname,'partnerID','partner','partnername = "'.$partnername.'" && partnertype="'.$partnertype4.'"');
                    if ($partner_location){
                        //Partner exists - Use it
                        $partnerhierarchy['location'] = $partner_location['partnerID'].'-'.$partnername;

                    } else {
                        //Partner does not exist create
                        $sql = 'INSERT INTO partner (partnertype,partnername,salesID,createdby,status) VALUES (?,?,?,?,?)';
                        $stmt = $pdo2->prepare($sql);
                        $stmt->execute([$partnertype4,$partnername,$salesID,$createdby,'1']);

                        //Get rowID of created partner and use it
                        $partner_rowid = $pdo2->lastInsertId();
                        $partnerhierarchy['location'] = $partner_rowid.'-'.$partnername;
                    }
                
                } else {
                    // Location exist use it
                    $partnerhierarchy['location'] = $partner_equipment->location;
                }

                $shipto = $partnerhierarchy['shipto'] ?? '';
                $partnerhierarchy = json_encode($partnerhierarchy, JSON_UNESCAPED_UNICODE);
                // --------------------------------------------
                // Update equipment record warranty_date, partnerhierarchy, status equipment
                // --------------------------------------------
                $sql = 'UPDATE equipment SET status = ?, warranty_date = ?, accounthierarchy = ?,updatedby = ? WHERE rowID = ?';
                $stmt = $pdo->prepare($sql);
                $stmt->execute(['4',$warranty_extended,$partnerhierarchy,$username,$rowID['rowID']]);

                //Add warranty to changelog
                $warranty_user = $post_content['email'] ?? 'system';
                changelog($dbname,'equipment',$rowID['rowID'],'Warranty',$warranty_extended,$warranty_user);

                //Serialnumber recognized
                $message_box[] = $sn.' - '.$register_message_3;
                $communication_check = 1;
                }
            } else {
                //Serialnumber not recognized
                $message_box[] = $sn.' - '.$register_message_1;
            }
        }
    } 
    else {
        // --------------------------------------------
        //Get equipmentid based on rowID
        // --------------------------------------------
        $rowID = getrowID($dbname,'rowID','equipment','serialnumber="'.$post_content['sn'].'"');
        if ($rowID){
            //check if under warranty
            $warranty = getrowID($dbname,'rowID','equipment_history','equipmentid="'.$rowID['rowID'].'" && (type="'.$type9.'" || type="'.$type10.'" || type="'.$type11.'" || type="'.$type12.'")');
            if ($warranty){
            // --------------------------------------------
            // Already under contract
            // --------------------------------------------
            //Serialnumber not recognized
            $message_box[] = $post_content['sn'].' - '.$register_message_2;
            } else
            {
            // --------------------------------------------
            // Not under warranty
            // --------------------------------------------
            $firmware_account_send = 1;
            //create history
            $sql = 'INSERT INTO equipment_history (equipmentid, type, description, created, createdby, updatedby) VALUES (?,?,?,?,?,?)';
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$rowID['rowID'],$type9,$description,$timestamp,$post_content['email'],$post_content['email']]);

            //GET PARTNER DETAILS OF EQUIPMENT
            $partner_equipment = getrowID($dbname,'accounthierarchy','equipment','rowID="'.$rowID['rowID'].'"');
            $partner_equipment = json_decode($partner_equipment['accounthierarchy']);

            //Setup partnerhierarchy (salesID)
            $partnerhierarchy =[
                "salesid"=>$partner_equipment->salesid,
                "soldto"=>$partner_equipment->soldto
            ];

            //Setup variables for partner
            $partnername = $post_content['organization'];
            $partnernotes = 'created based on user registration';
            $salesID = json_encode($partnerhierarchy, JSON_UNESCAPED_UNICODE);
            $createdby = 'system';

            //Check if shipto is empty and if empty search partner or create
            if ($partner_equipment->shipto == ''){
                $partner_shipto = getrowID($dbname,'partnerID','partner','partnername = "'.$partnername.'" && partnertype="'.$partnertype3.'"');
                if ($partner_shipto){
                    //Partner exists - Use it
                    $partnerhierarchy['shipto'] = $partner_shipto['partnerID'].'-'.$partnername;
                } else {
                    //Partner does not exist create
                    $sql = 'INSERT INTO partner (partnertype, partnername,salesID,createdby,status) VALUES (?,?,?,?,?)';
                    $stmt = $pdo2->prepare($sql);
                    $stmt->execute([$partnertype3,$partnername,$salesID,$createdby,'1']);

                    //Get rowID of created partner and use it
                    $partner_rowid = $pdo2->lastInsertId();
                    $partnerhierarchy['shipto'] = $partner_rowid.'-'.$partnername;
                }
            } else {
                // Shipto exist use it
                $partnerhierarchy['shipto'] = $partner_equipment->shipto;
            }
            //Check if location is empty and if empty search partner or create
            if ($partner_equipment->location == ''){
                $partner_location = getrowID($dbname,'partnerID','partner','partnername = "'.$partnername.'" && partnertype="'.$partnertype4.'"');
                if ($partner_location){
                    //Partner exists - Use it
                    $partnerhierarchy['location'] = $partner_location['partnerID'].'-'.$partnername;

                } else {
                    //Partner does not exist create
                    $sql = 'INSERT INTO partner (partnertype,partnername,salesID,createdby,status) VALUES (?,?,?,?,?)';
                    $stmt = $pdo2->prepare($sql);
                    $stmt->execute([$partnertype4,$partnername,$salesID,$createdby,'1']);

                    //Get rowID of created partner and use it
                    $partner_rowid = $pdo2->lastInsertId();
                    $partnerhierarchy['location'] = $partner_rowid.'-'.$partnername;
                }
            } else {
                // Location exist use it
                $partnerhierarchy['location'] = $partner_equipment->location;
            }

            $partnerhierarchy = json_encode($partnerhierarchy, JSON_UNESCAPED_UNICODE);
           
            // --------------------------------------------
            // Update equipment record warranty_date, partnerhierarchy, status equipment
            // --------------------------------------------
            $sql = 'UPDATE equipment SET status = ?, warranty_date = ?, accounthierarchy = ?, updatedby = ? WHERE rowID = ?';
            $stmt = $pdo->prepare($sql);
            $stmt->execute(['4',$warranty_extended,$partnerhierarchy,$username,$rowID['rowID']]);

            //Add warranty to changelog
            $warranty_user = $post_content['email'] ?? 'system';
            changelog($dbname,'equipment',$rowID['rowID'],'Warranty',$warranty_extended,$warranty_user);

            //Serialnumber recognized
            $message_box[] = $post_content['sn'].' - '.$register_message_3;
            }
        }
        else {
            //Serialnumber not recognized
            $message_box[] = $post_content['sn'].' - '.$register_message_1;
        }
    }   

    // --------------------------------------------
    // Send generic account to user for software updates
    // --------------------------------------------
    if ($firmware_account_send == 1){
        include_once './assets/mail/email_template_software.php';
        send_mail($post_content['email'],$subject,$message,'','');
    }

    // ----------------------------------------------
    // Create communication user when not exist
    // ----------------------------------------------
    if ($communication_check == 1 && isset($shipto) && $shipto !=''){
        //Check if communication record exist
        $rowID = getrowID($dbname,'rowID','communication','partnerID ="'.$shipto.'" and email = "'.$post_content['email'].'"');

        if ($rowID){
            //communication record exist
        }
        else
        {
            //communication record does not exist ->create
            $sql = 'INSERT INTO communication (status,partnerID,email,type_1,type_2,type_3,createdby,salesID,coms_type) VALUES (?,?,?,?,?,?,?,?,?)';
            $stmt = $pdo->prepare($sql);
            $stmt->execute(['1',$shipto,$post_content['email'],'1','1','1',$createdby,$salesID,'1']);
        }
    }
    
    //Encrypt results
    $messages = generate_payload($message_box);
    //Send results
    echo $messages;
  
    // --------------------------------------------
    // END User registration
    // --------------------------------------------
    break;

    case 'firmwareCommunication':
        if (isset($post_content['hw_version']) && $post_content['hw_version'] != ''){

            include './settings/systemfirmware.php';
        
            $target = $post_content['target'] ?? '0';
    
            //FILTER VARIABLES FOR SQL
            $filter1 = 'soldto":"';
            $filter2 = '","shipto';
            $filter3 = 'shipto":"';
            $filter4 = '","location';
    
            //ADD additional createria to whereclause (Firmware and Active)
            $whereclause .= " e.hw_version= ? AND c.type_1='1' AND c.status='1' AND e.status != 5 AND (e.sw_version != '$FirmwarenameR06' OR e.sw_version != '$FirmwarenameR06A' OR e.sw_version != '$FirmwarenameR07A' OR e.sw_version != '$FirmwarenameR07B' OR  e.sw_version != '$FirmwarenameR07' OR e.sw_version != '$FirmwarenameR08')";

            //get target
            switch ($target) {
                case '0': // Both
                    $onclause ="SUBSTRING_INDEX(SUBSTRING_INDEX(e.accounthierarchy, '$filter1', -1),'$filter2',1) = c.partnerID or SUBSTRING_INDEX(SUBSTRING_INDEX(e.accounthierarchy, '$filter3', -1),'$filter4',1) = c.partnerID";
                    break;
                
                case '1': // SoldTO only
                    $onclause ="SUBSTRING_INDEX(SUBSTRING_INDEX(e.accounthierarchy, '$filter1', -1),'$filter2',1) = c.partnerID";
                    break;
                
                case '2': // ShipTO only
                    $onclause =" SUBSTRING_INDEX(SUBSTRING_INDEX(e.accounthierarchy, '$filter3', -1),'$filter4',1) = c.partnerID";
                    break;
            }
            
            //CHECK IF WHERE CLAUSE CONTAINS WHERE

            //GET THE FULL LIST OF COMMUNCATION RECORDS FOR FIRMWARE MESSAGE
            $sql = "SELECT e.sw_version, c.email from equipment e join communication c on $onclause $whereclause group by c.email";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$post_content['hw_version']]);
            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

            if ($results) {
                //IF RESULTS ARE RETURNED
                foreach ($results as $result) {
                    //LOOP OVER ALL RESULTS AND SET SEND_INDICATOR to 1
                    $sql = "UPDATE communication SET send_indicator = 1 WHERE email = ?";
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute([$result['email']]);
                }
                //------------------------------------------
                //Encrypt results
                //------------------------------------------
                $messages = generate_payload('200');

                //------------------------------------------
                //Send results
                //------------------------------------------
                echo $messages; 

            } 
            else {
                http_response_code(200);
            }

        }
        else {
                http_response_code(400);
        }
    break;
}

}
