<?php
$allow = array("185.51.188.174", "37.234.69.4" ); //allowed IPs

// function tomb2($t) {return "<pre style='color:red'>". print_r($t)."</pre>"; }


// if(in_array($_SERVER['REMOTE_ADDR'], $allow) ) {
	
	$hostname_conDB = "localhost";
	$database_conDB = "vetmedla_web";
	$username_conDB = "vetmedla_web";
	$password_conDB = "Siker1515";
	$elotag = "zbt7h";

	// Create connection
	$CDB = new mysqli($hostname_conDB, $username_conDB, $password_conDB, $database_conDB);

	// Check connection
	if ($CDB->connect_error) {
	    die("Connection failed: " . $conn->connect_error);
	} 
	//[ expired, none, outstanding, paid, partially_paid ]

	$sql = "SELECT * FROM ".$elotag."_ati_egyedi WHERE szamla_id>0 AND szamla_stat !='paid'";
	$ds = $CDB->query($sql);

	$log = 'FUT: ';
    while($row = $ds->fetch_assoc()) {
		// tomb2($row);
		$headers = array(
		    $row['szamla_head'],
		    'accept: application/json'
		);

		$log .= $row['szamla_szama']." - ".$row['szamla_stat']." :: ";



        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,"https://api.billingo.hu/v3/documents/".$row['szamla_id']);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET' );
        // curl_setopt($ch, CURLOPT_POSTFIELDS,$postvars);  //Post Fields
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $result = curl_exec ($ch);
        curl_close ($ch);
        $r = json_decode($result, true);
		// tomb2($r);
		if (!empty($r['id'])) {

			$sql = "UPDATE ".$elotag."_ati_egyedi SET szamla_stat='".$r['payment_status']."' WHERE szamla_id=".$r['id'];
			$result = $CDB->query($sql);
			
			if ($r['payment_status'] == 'paid') {

				//log
				$log .= $row['szamla_szama']." - Fizetve :: ";

				// megrendeles tetel statusz
				$sql = "UPDATE ".$elotag."_virtuemart_order_items SET order_status='F' WHERE 
								virtuemart_order_item_id=".$row['rend_tetel_id']." AND 
								virtuemart_order_id=".$row['rend_id'];
				$result = $CDB->query($sql);
				//log
				$log .= $row['szamla_szama']." - Megrend tetelek modositva :: ";

				// user hozzarendeles

				if ($row['szeri_stat'] == 'done_signed_contract') {
					$sql = "INSERT ".$elotag."_user_usergroup_map SET user_id='".$row['user']."', group_id='".$row['group']."'";
					$result = $CDB->query($sql);
					//log
					$log .= $row['szamla_szama']." - User group kiosztva ".$row['user'].":".$row['group']." :: ";
				}
			}
		}
	}

	$sql = "INSERT ".$elotag."_ati_egyedi_cron SET esemeny='".$log."'";
	$result = $CDB->query($sql);


// } else {
//  die('NYET: '.print_r($_SERVER['REMOTE_ADDR']));
// } 


?>