<?php
require_once 'config/config.php';
$totallimit = 40;
$db = getDbInstance();
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
    //Mass Insert Data. Keep "name" attribute in html form same as column name in mysql table.
    $data_to_store = array_filter($_POST);
    $db->where('amember', $data_to_store['amember']);
    //Get data to pre-populate the form.
    $charges = $db->getOne("charges");
		$db = getDbInstance();
		$left = $totallimit;

		if (!$charges) {
  		$last_id = $db->insert('charges', array(
        "amember" => $data_to_store['amember'],
        'total' => $totallimit,
        'charges' => $totallimit,
        'last_recharge' => time()
      ));
		} else {
			$left = $charges['charges'];
		}

		if ($left > 0) {
			$data_to_store['charges'] = $left;
			$data_to_store['when'] = time();
			$db->insert('actions', $data_to_store);

			$left = $left - 1;
			$db = getDbInstance();
		 	$db->where('amember',$_POST['amember']);
	    $db->update('charges', array(
				"charges" => $left
			));
			echo "[OK]";
		}
} elseif (isset($_GET['amember'])) {
	$db->where('amember', $_GET['amember']);
	//Get data to pre-populate the form.
	$charges = $db->getOne("charges");
	$left = $totallimit;
	if (!$charges) {
    $last_id = $db->insert('charges', array(
      "amember" => $_GET['amember'],
      'total' => $totallimit,
      'charges' => $totallimit,
      'last_recharge' => time()
    ));
	} else {
		$left = $charges['charges'];
	}
	echo $left;
}
