<?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->addMessage($ex->getMessage());
  $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   c.internalCircuitNumber 'name',
  ma.customerName 'customer',
  case
    when op.displayValue is null then opp.displayValue
    else op.displayValue
  end 'service_type',
  s.username 'sub_account',
  c.customerCompanyName 'side_a',
  c.internalCircuitNumber 'circuit_id',
  c.siteA 'pop',
  so5.displayValue AS 'account_status',
  null 'resource_status',
  s.ispMasterAccountId masterAccountId,
  ma.billingMasterAccountId,
  case
    when op.insertValue is null then opp.insertValue
    else op.insertValue
  end 'service_type_id',
  ma.accountId,
  pds.promoCode 'networktype',
  s.id 'serviceAccountId',
  ma2.id 'locationMasterAccountId',
  c.nniCircuitId,products.ticketTypeId , ticket_types.name 'department'
from
  logical_circuit c
  left join service_accounts s on s.id = c.serviceAccountId
  LEFT JOIN master_accounts ma ON c.ispMasterAccountId = ma.id
  LEFT JOIN master_accounts ma2 ON s.masterAccountId = ma2.id
  LEFT JOIN order_tx_lines p ON p.serviceAccountId = s.id
  LEFT JOIN tickets ON tickets.ticketserviceAccountId = s.id
  left outer join promo_code_products pcp on pcp.id = c.promocodeproductid
  left join promo_codes pds on pds.id = pcp.promoCodeId
  LEFT JOIN products ON products.id = pcp.productid
  LEFT JOIN select_options so5 ON s.statusId = so5.optionKey
  left join service_type_parameter_options op on op.insertValue = LEFT(c.internalCircuitNumber, 2)
  and servicetypeparameterid = 7357002
  LEFT JOIN service_instances si ON s.id = si.serviceAccountId
  left join sv_link_africa_fibre_service_account a on a.serviceAccountId = s.id
  left join service_type_parameter_options opp on opp.insertValue = IF(a.productTypeId = 0, 32, a.productTypeId)
    LEFT JOIN ticket_types ON ticket_types.id =  products.ticketTypeId
WHERE
  so5.groupId = 79  ");

              $query->execute();

              $rowCount = $query->rowCount();

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



                    $systemId = 2; // solid
                    $name = is_null($row['name'])  ? NULL : str_replace("'", "",$row['name']) ;
                    $customer = is_null($row['customer'])  ? NULL : str_replace("'", "",$row['customer']);
                    $service_type = is_null($row['service_type'])  ? NULL : $row['service_type'];
                    $sub_account = is_null($row['sub_account'])  ? NULL : $row['sub_account'];
                    $side_a = is_null($row['side_a'])  ? NULL : str_replace("'", "",$row['side_a']);
                    $pop = is_null($row['pop'])  ? NULL : $row['pop'];
                    $circuit_id = is_null($row['circuit_id'])  ? NULL : $row['circuit_id'];
                    $account_status = is_null($row['account_status'])  ? NULL : $row['account_status'];
                    $resource_status = is_null($row['resource_status'])  ? NULL : $row['resource_status'];
                    $masterAccountId = is_null($row['masterAccountId'])  ? NULL : $row['masterAccountId'];
                    $billingMasterAccountId = is_null($row['billingMasterAccountId'])  ? NULL : $row['billingMasterAccountId'];
                    $service_type_id = is_null($row['service_type_id'])  ? NULL : $row['service_type_id'];
                    //$networktypeid = is_null($row['networktypeid'])  ? NULL : $row['networktypeid'];
                    $networktype = is_null($row['networktype'])  ? NULL : $row['networktype'];
                    $serviceAccountId = is_null($row['serviceAccountId'])  ? NULL : $row['serviceAccountId'];
                    $locationMasterAccountId = is_null($row['locationMasterAccountId'])  ? NULL : $row['locationMasterAccountId'];
                    $nniCircuitId = is_null($row['nniCircuitId'])  ? NULL : $row['nniCircuitId'];
                    $ticketTypeId = is_null($row['ticketTypeId'])  ? NULL : $row['ticketTypeId'];
                    $department = is_null($row['department'])  ? NULL : $row['department'];


                    $obj = new logic();
                    $loc = $obj->lookup_Location($locationMasterAccountId,$systemId);
                    //$sub = $obj->lookup_Sub_account($masterAccountId,$systemId,$sub_account);

                    $com = $obj->lookup_companyMasterAccountid($billingMasterAccountId,$systemId);


                    $companyMasterAccountId =  $com->id;
                    $locationid = $loc->id;

                    $flag = $obj->check_service_by_tag($systemId,$name);

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

                    if ($flag == 0)
                        {

                        $obj->add_service($service_type_id,$companyMasterAccountId,$locationid,$uniqid_key,$systemId,$name,$customer,$service_type,$sub_account,$side_a,$pop,$circuit_id,$account_status,$resource_status,$masterAccountId,$nniCircuitId,$serviceAccountId,$networktype,$ticketTypeId);
                        $rowCount = $rowCount + 1;

                        }
                        else {

                        //    $obj->update_service_ticketTypeId_cur ($circuit_id,$systemId,$ticketTypeId,$department);

                         //$obj->update_service_la($serviceAccountId,$networktype,$networktypeid,$name,$service_type,$service_types_id,$companyMasterAccountId,$locationid,$systemId,$customer,$side_a,$account_status,$resource_status,$masterAccountId,$sub_account);

                         //$rowCount =  $rowCount + 1;

                        }


                }

        $ob = new logic();
        $ob->update_service_systemId_LA();
        $response = new Response();
        $response->setSuccesss(true);
        $response->sethttpStatusCode(200);
        $response->addMessage((string) $rowCount . " record inserted into central database.");
        $response->addMessage('LA 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();

}
