<?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/sales.php';
include_once '../objects/message.php';

$database = new Database();
$db = $database->getConnection();
 
$sales = new Sales($db);
$message = new Message($db);
$data = json_decode(file_get_contents("php://input"));

$sales->id_no = $data->id_no;
$sales->start_date = $data->start_date;
$sales->extra_days = $data->extra_days;
// $sales->end_date = $data->end_date;

if($data->id_no){

	if($sales->updateAssign()){

		$msg_detail = $message->getMsg("d_assign");
		$token = "";
		$sales->id=$data->id;
		$stmt = $sales->getSMSByID($sales->id);
		$num = $stmt->rowCount();
		if($num>0){
			while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
				extract($row);
	
				$healthy = ["[ID]", "[Plan]", "[Start_Date]", "[End_Date]", "[Amount]", "[Today_Date]", "[Invoice_No]", "[Hotline]"];
				$yummy   = [$id_no, $mbps."MB ".$days."Days", $start_date, $end_date, number_format($payment), $sales->date, $invoice_no, $ph_no];
	
				$data = [
					// "to"        =>      '09969002859',
					"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");
	
			}
		}

		$msg_arr = array(
			"message" => "updated"
		);
	}else{
		$msg_arr = array(
			"message" => "error"
		);
	}
}
echo json_encode($msg_arr);
?>	