<?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);



try {


  $readDB = DB::connectReadDB();

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


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',
p.firstName,
p.lastName,
so4.displayValue 'role',
p.workNumber,
p.cellNumber,
p.emailAddress,
ma2.customerName 'company',
ma.customerName 'location',
ma.billingMasterAccountId,
p.id 'people_id'
FROM
master_accounts ma
LEFT JOIN master_accounts ma2 ON ma.billingMasterAccountId = ma2.id
left JOIN people p ON ma.id = p.masterAccountId
left join addresses ad on ad.masterAccountId = ma.id
left join select_options so on so.optionKey = ad.physicalProvinceId
left JOIN select_options so2 ON ma.statusId = so2.optionKey
left JOIN select_options so3 ON ma.accountTypeId = so3.optionKey
left JOIN select_options so4 ON p.contactTypeId = so4.optionKey
WHERE
so2.groupId = 17
and so3.groupId = 18
and so4.groupId = 34
and so.groupId = 8
and so.optionKey not in (40)
and p.emailAddress is not null
");

              $query->execute();

              $rowCount = $query->rowCount();

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



                  $systemId = 2; // Solid LA

               $masterAccountId = is_null($row['masterAccountId'])  ? NULL : $row['masterAccountId']; //Company Account id
               $code = is_null($row['code'])  ? NULL : $row['code'];
               $location = is_null($row['location'])  ? NULL : str_replace("'", "",$row['location']);
               $company = is_null($row['company'])  ? NULL : str_replace("'", "",$row['company']) ;
               $emailAddress  = is_null($row['emailAddress'])  ? NULL : $row['emailAddress'];
               $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'];
               $billingMasterAccountId = is_null($row['billingMasterAccountId'])  ? NULL : $row['billingMasterAccountId'];
               $people_id =  is_null($row['people_id'])  ? NULL : $row['people_id'];
               $role = is_null($row['role'])  ? NULL : $row['role'];



                    $obj = new logic();



                    $flag = $obj->check_user($people_id,$systemId);

                    if ($flag == 0)
                        {

                            //echo "<br/> ---Added---<br/>";
                              $obj->add_contact_details ($systemId,$firstName,$lastName,$emailAddress,$code,$role,$masterAccountId,$location,$company,$billingMasterAccountId,$workNumber,$cellNumber,$people_id);
                            $rowCount = $rowCount + 1;

                        }


                }





        $response = new Response();
        $response->setSuccesss(true);
        $response->sethttpStatusCode(200);
        $response->addMessage((string) $rowCount . " record inserted into central database.");
        $response->addMessage('BitCo 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("Endpoint not found");
  $response->send();

}
