<?php
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");
    header("Access-Control-Allow-Methods: POST");
    header("Access-Control-Max-Age: 3600");
    header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

	include_once 'config/database.php';
	include_once 'objects/sales.php';
    include_once 'objects/ont.php';
    include_once 'objects/ont_status.php';

	date_default_timezone_set('Asia/Rangoon'); 
	session_start();
	$database = new Database();
	$db = $database->getConnection();
	 
	$sales = new Sales($db);
    $ont = new ONT($db);
    $ont_status = new OntStatus($db);

    $data = json_decode(file_get_contents("php://input"));

	$arr=array();

    $arr["detailREM"]=array();
	$sales->td = date('Y-m-d');
		$sales->d = date('Y-m-d',(strtotime ( '-1 day' , strtotime ( date("Y-m-d") ) ) ));
		$stmt = $sales->getToDisableList("");

$hasData = false;

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
    $hasData = true;

    extract($row);

    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://tkknet.smartolt.com/api/onu/disable/'.$ont_snno,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_HTTPHEADER => array(
            'X-Token: ' . $smart_key
        ),
    ));

    $response = curl_exec($curl);
    curl_close($curl);

    $response = json_decode($response);

    if($response && $response->status){

        $ont->id_no = $id_no;
        $ont->status = 2;

        $ont_status->id_no = $id_no;
        $ont_status->invoice_no = $invoice_no;
        $ont_status->status = 2;
        $ont_status->entry_by = "cron";
        $ont_status->entry_date_time = date("Y-m-d H:i:s");    

        $ont->updateStatus();
        $ont_status->create();

        $arr["detailREM"][] = [
            "id_no" => $ont_snno,
            "status" => "sent"
        ];

    } else {
        $arr["detailREM"][] = [
            "id_no" => $ont_snno,
            "status" => "error"
        ];
    }
}

if(!$hasData){
    $arr["detailREM"] = [];
}

echo json_encode($arr);
?>