<?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 required files
include_once '../config/database.php';
include_once '../objects/createrole.php';

// Create a database connection
$database = new Database();
$db = $database->getConnection();

// Initialize UserRole object
$userrole = new UserRole($db);

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

// Validate input data
if (!isset($data->id) || !isset($data->rolename) ) {
    echo json_encode(array("message" => "Invalid input"));
    exit;
}

// Set properties
$userrole->id = $data->id;
$userrole->rolename = $data->rolename;
$userrole->create_role = $data->create_role;
$userrole->employee = $data->employee;
$userrole->create_account = $data->create_account;
$userrole->change_password = $data->change_password;
$userrole->investor = $data->investor;
$userrole->room = $data->room;
$userrole->agent = $data->agent;
$userrole->item = $data->item;
$userrole->duty_schedule = $data->duty_schedule;
$userrole->attendance = $data->attendance;
$userrole->attendance_update = $data->attendance_update;
$userrole->reservation = $data->reservation;
$userrole->upcoming_arrivals = $data->upcoming_arrivals;
$userrole->arrival = $data->arrival;
$userrole->occupied_list = $data->occupied_list;
$userrole->deleted_reservation_list = $data->deleted_reservation_list;
$userrole->sales_service = $data->sales_service;
$userrole->stock_in = $data->stock_in;
$userrole->stock_out = $data->stock_out;
$userrole->stock_in_report = $data->stock_in_report;
$userrole->stock_out_report = $data->stock_out_report;
$userrole->stock_balance_report = $data->stock_balance_report;
$userrole->purchase = $data->purchase;
$userrole->purchase_report = $data->purchase_report;
$userrole->monthly_report = $data->monthly_report;
$userrole->cash_book_report = $data->cash_book_report;
$userrole->coa = $data->coa;
$userrole->expense = $data->expense;
$userrole->income = $data->income;
$userrole->expense_report = $data->expense_report;
$userrole->income_report = $data->income_report;
$userrole->attendance_report = $data->attendance_report;
$userrole->guest_report = $data->guest_report;
$userrole->arrival_report = $data->arrival_report;
$userrole->departure_report = $data->departure_report;

// Check for duplicates and create role
if($data->id){
    if($userrole->update()){
        echo json_encode(array("message" => "updated"));
    }
}else{
    if($userrole->exist()){
        echo json_encode(array("message" => "duplicate"));
    } else if($userrole->create()){
        echo json_encode(array("message" => "created"));
    } else {
        echo json_encode(array("message" => "error"));
    }
}
?>
