<?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/agent.php'; 

session_start();
date_default_timezone_set('Asia/Rangoon');

$database = new Database();
$db = $database->getConnection();

$agent = new Agent($db);

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

$agent->id = isset($data->id) ? $data->id : null;
$agent->agent_name = isset($data->agent_name) ? $data->agent_name : null;
$agent->commission = isset($data->commission) ? $data->commission : 0;
$agent->phone = isset($data->phone) ? $data->phone : null;
$agent->email = isset($data->email) ? $data->email : null;
$agent->address = isset($data->address) ? $data->address : null;
$agent->remark = isset($data->remark) ? $data->remark : null;
$agent->inactive = isset($data->inactive) ? $data->inactive : 0;
$agent->entry_by = isset($_SESSION['userid']) ? $_SESSION['userid'] : "";
$agent->update_by = isset($_SESSION['userid']) ? $_SESSION['userid'] : "";

if ($data->id) {
    if ($agent->update()) {
        echo json_encode(array("message" => "updated"));
    } else {
        echo json_encode(array("message" => "error"));
    }
} else {
    if ($agent->exist()) {
        echo json_encode(array("message" => "duplicate"));
    } elseif ($agent->create()) {
        echo json_encode(array("message" => "created"));
    } else {
        echo json_encode(array("message" => "error"));
    }
}
?>
