<?php
// required headers
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/ont.php';
include_once '../objects/sales.php';
include_once '../objects/ont_status.php';
include_once '../objects/message.php';
date_default_timezone_set('Asia/Rangoon');
session_start();
$database = new Database();
$db = $database->getConnection();
 
$ont = new ONT($db);
$sales = new Sales($db);
$ont_status = new OntStatus($db);
$message = new Message($db);
$data = json_decode(file_get_contents("php://input"));


$ont_status->entry_by = isset($_SESSION['user'])?$_SESSION['user']:"";
$ont_status->entry_date_time = date("Y-m-d H:i:s");	
$sales->id_no = $data->id_no;
$ont->id_no = $data->id_no;
$sales->invoice_no = $data->invoice_no;
$ont_status->invoice_no = $data->invoice_no;

        $ont_status->status = 1;
        $ont->status = 1;
        $ont->updateStatus();
        $sales->start_date =  $data->date;
        $sales->updateStartDate();

        $msg_detail = $message->getMsg("d_assign");
        $token = "";
        $stmt = $sales->getSMSByInvoiceNo($data->invoice_no);
        $num = $stmt->rowCount();
        if($num>0){
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
                extract($row);
    
                $healthy = ["[ID]", "[Plan]", "[Start_Date]", "[End_Date]", "[Hotline]"];
                $yummy   = [$id_no, $package, $start_date, $end_dates, $ph_no];
    
                $data = [
                    "to"        =>      $phone,
                    "message"   =>      str_replace($healthy, $yummy, $msg_detail),
                ];
    
                $ch = curl_init("https://smspoh.com/api/v2/send");
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
                        // 'Authorization: Bearer RCZwPzftQwmUfuYfOeBjH2WICaTffqJIH82-_EBT6OXZzut4-tcxn5jkP2PUFfdV',
                        'Content-Type: application/json'
                    ]);
            
                    curl_exec($ch);
                    
                    $sales->updateSMS("d_assign");
    
            }
        }


    $ont_status->id_no = $data->id_no;
    if($ont_status->create()){
        $msg_arr = array(
            "message" => "updated"
        );
    }else{
        $msg_arr = array(
            "message" => "error"
        );
    }


echo json_encode($msg_arr);
?>	