<?php
use \bitco\logic;


require_once ('db.php');
require_once ('../model/Task.php');
require_once ('../model/Response.php');
require_once ('../class/logic.php');



ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

//$page =  $_GET['page'];
//$limitPerPage = 20;
//$offset = ($page == 1 ? 0 : ($limitPerPage*($page-1)));

//$num = 200;

//echo $offset;
//exit();

try {


  $readDB = DB::connectReadDB();

} catch (PDOException $ex) {
  $response = new Response();
  $response->setSuccesss(false);
  $response->sethttpStatusCode(500);
  $response->addMessage("Database connection error");
  $response->send();
    exit();
}


function generateRandomString($length = 10) {
return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}


if(!isset($_SERVER['HTTP_AUTHORIZATION'])  || strlen($_SERVER['HTTP_AUTHORIZATION'])  < 1 ){


    $response = new Response();
    $response->setSuccesss(false);
    $response->sethttpStatusCode(401);
    (!isset($_SERVER['HTTP_AUTHORIZATION']) ? $response->addMessage('Access Token is missing from the header') : false);
    (strlen($_SERVER['HTTP_AUTHORIZATION'])  < 1   ? $response->addMessage('Access token cannot be blank') : false);
    $response->send();
      exit();
}


 $accesstoken = $_SERVER['HTTP_AUTHORIZATION'];



    if ($accesstoken !== 'NDUzY2RlYzFhMWRhNTAU9xZDhhYzI0YTA5MTcTA3NTE2OA=='){
    $response = new Response();
    $response->setSuccesss(false);
    $response->sethttpStatusCode(400);
    $response->addMessage("Invalid Access Token");
    $response->send();
    exit();
  }



if (empty($_POST)){



    if  ($_SERVER['REQUEST_METHOD'] == 'POST'){

    try {

              $query = $readDB->prepare(" SELECT
  DISTINCT ma.id 'code',
  ma2.accountId 'masterAccountId',
  ma.parentMasterAccountId,
  ma.customerName 'location',
  ma2.customerName 'company',
  ma.accountId AS 'identifier',
  p.emailAddress,
  so2.displayValue AS 'account_status',
  so3.displayValue AS 'account_type',
  ad.physicalLine1 'address',
  ad.physicalSuburb 'suburb',
  ad.physicalCity 'city',
  p.firstName,
  p.lastName,
  p.cellNumber,
  p.workNumber,
  p.job,
  ad_bill.physicalLine1 'company_address',
  ad_bill.physicalCity 'company_city',
  org.name organization_name,
  org.country,
  ma.billingMasterAccountId,
  u.latitude 'physicalLatitude',
  u.longitude 'physicalLongitude',
  so4.displayValue 'province',
   au.firstName AS 'manager_firstName',
    au.lastName AS 'manager_lastName',
    au.emailAddress AS 'manager_email',
    ma.uid,u.provinceId
FROM
  master_accounts ma
  LEFT JOIN master_accounts ma2 ON ma.billingMasterAccountId = ma2.id
  LEFT JOIN contracts ON contracts.masterAccountId = ma.id
  LEFT JOIN products ON contracts.productId = products.id
  left JOIN people p ON ma.primaryContact = p.id
  left join addresses ad on ad.masterAccountId = ma.id
  left join addresses ad_bill on ad_bill.masterAccountId = ma2.id
  LEFT JOIN admin_users au ON ma.supportManagerId = au.id
  LEFT JOIN select_options so2 ON ma.statusId = so2.optionKey
  left JOIN select_options so3 ON ma2.accountTypeId = so3.optionKey
  left join uids u on u.uid = ma.uid
  left JOIN select_options so4 ON so4.optionKey = IF(
    u.provinceId = 0,
    99,
    u.provinceId
  )
  left JOIN organizations org ON org.id = ma2.organizationId
WHERE
 so4.groupId = 3652 and
  so2.groupId = 17
  and so3.groupId = 18

              ");

              $query->execute();

              $rowCount = $query->rowCount();

                $taskArray = [];
                  $rowCount = 0;
                while ($row = $query->fetch(PDO::FETCH_ASSOC)){



                    $systemId = 2; // Solid Link Africa
                    $masterAccountId = is_null($row['masterAccountId'])  ? NULL : $row['masterAccountId']; //Company Account id
                    $code = is_null($row['code'])  ? NULL : $row['code']; // primary master id
                    $parentMasterAccountId = is_null($row['parentMasterAccountId'])  ? NULL : $row['parentMasterAccountId'];
                    $location = is_null($row['location'])  ? NULL : str_replace("'", "",$row['location']);
                    $company = is_null($row['company'])  ? NULL : str_replace("'", "",$row['company']) ;
                    $identifier = is_null($row['identifier'])  ? NULL : $row['identifier']; //  branch/site master id
                    $emailAddress  = is_null($row['emailAddress'])  ? NULL : $row['emailAddress'];
                    $account_status = is_null($row['account_status'])  ? NULL : $row['account_status'];
                    $account_type = is_null($row['account_type'])  ? NULL : $row['account_type'];
                    $address = is_null($row['address'])  ? NULL : str_replace("'", "",$row['address']);
                    $suburb = is_null($row['suburb'])  ? "" : str_replace("'", "",$row['suburb']);
                    $city =  is_null($row['city'])  ? NULL : str_replace("'", "",$row['city']) ;
                    $firstName =  is_null($row['firstName'])  ? NULL : str_replace("'", "",$row['firstName']);
                    $lastName =  is_null($row['lastName'])  ? NULL : str_replace("'", "",$row['lastName']);
                    $cellNumber =  is_null($row['cellNumber'])  ? NULL : $row['cellNumber'];
                    $workNumber = is_null($row['workNumber'])  ? NULL : $row['workNumber'];
                    $job = is_null($row['job'])  ? NULL : $row['job'];
                    $company_address  = is_null($row['company_address'])  ? "" : str_replace("'", "",$row['company_address']) ;
                    $company_city  = is_null($row['company_city'])  ? "" : str_replace("'", "",$row['company_city']);
                    $organization_name = is_null($row['organization_name'])  ? NULL : $row['organization_name'];
                    $country = is_null($row['country'])  ? NULL : $row['country'];
                    $companyMasterAccountId = is_null($row['billingMasterAccountId'])  ? NULL : $row['billingMasterAccountId'];


                    $physicalLatitude = is_null($row['physicalLatitude'])  ? NULL : $row['physicalLatitude'];
                    $physicalLongitude = is_null($row['physicalLongitude'])  ? NULL : $row['physicalLongitude'];
                    $province = is_null($row['province'])  ? NULL : $row['province'];

                    $manager_firstName = is_null($row['manager_firstName'])  ? NULL : $row['manager_firstName'];
                    $manager_lastName = is_null($row['manager_lastName'])  ? NULL : $row['manager_lastName'];
                    $manager_email = is_null($row['manager_email'])  ? NULL : $row['manager_email'];
                    $uid = is_null($row['uid'])  ? NULL : $row['uid'];
                    $provinceId = is_null($row['provinceId'])  ? NULL : $row['provinceId'];



                    $parentMasterAccountId = 1; //override

                    $obj = new logic();

                    $flag = $obj->check_company_exists($masterAccountId,$systemId);

                      $uniqid_key =  uniqid('la_'. date("d")."_". date("m")."_".date("y")."__");

                    if ($flag == 0)
                        {

                            //echo "<br/> ---Added---<br/>";

                              $obj->add_company($companyMasterAccountId,$uniqid_key,$systemId,$masterAccountId,$code,$parentMasterAccountId,$location,$company,$identifier,$emailAddress,$account_status,$account_type,
                            $address,$suburb,$city,$firstName,$lastName,$cellNumber,$workNumber,$job,$company_address,
                            $company_city,$organization_name,$country,$physicalLatitude,$physicalLongitude,$province);
                            $rowCount = $rowCount + 1;


                        }

                         else {
                            //  $rowCount = $rowCount + 1;
                              //$obj->update_company_la ($systemId,$masterAccountId,$code,$location,$company,$identifier,$emailAddress,$account_status,
                          //  $address,$suburb,$city,$firstName,$lastName,$cellNumber,$workNumber,$job,$company_address,$company_city,$physicalLatitude,$physicalLongitude,$province,$manager_firstName,$manager_lastName,$manager_email,$uid,$provinceId);
                          }


                }


                $obj2 = new logic();

                $obj2->update_system_id_bitco();
                $obj2->update_system_id_la();
                $obj2->update_system_id_o2cap();


        $response = new Response();
        $response->setSuccesss(true);
        $response->sethttpStatusCode(200);
        $response->addMessage((string) $rowCount . " record inserted/updated into central database.");
        $response->addMessage('O2CAP Solid : Action Successfully Completed');
        $response->send();
        exit();

    } catch (PDOException $eX) {
      $response = new Response();
      $response->setSuccesss(false);
      $response->sethttpStatusCode(501);
      $response->addMessage($ex->getMessage());
      $response->send();
      exit();
    }



    }


    else
        {
            $response = new Response();
            $response->setSuccesss(false);
            $response->sethttpStatusCode(404);
            $response->addMessage("Request method not allowed");
            $response->send();
        }

}else {
  // code...
  $response = new Response();
  $response->setSuccesss(false);
  $response->sethttpStatusCode(404);
  $response->addMessage("Request method not allowed");
  $response->send();

}
