<?php
header('Content-Type: application/json');
date_default_timezone_set("Asia/Kolkata");

include('DB.php');

$raw = file_get_contents('php://input');
$input = json_decode($raw, true);

if (is_array($input) && isset($input['action'])) {
    $action = $input['action'];
} elseif (isset($_POST['action'])) {
    $action = $_POST['action'];
} else {
    $action = null;
}



if ($action === 'load') {
	$bdd = new DB();

	$user_id = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
	$rows = $bdd->getAll("SELECT * FROM user_permissions WHERE user_id = ?",[$user_id]);

	echo json_encode($rows);
	$bdd->disconnect();
	exit;
} else if ($action === 'save') {
	$bdd = new DB();

	$data = json_decode(file_get_contents('php://input'), true);

	$user_id = (int)$data['user_id'];
	$permissions = $data['permissions'];

	foreach ($permissions as $perm) {

		$page_key = $perm['page_key'];
		$can_view = (int)$perm['can_view'];
		$can_edit = (int)$perm['can_edit'];
		$can_delete = (int)$perm['can_delete'];

		// check if row exists
		$exists = $bdd->getOne(
			"SELECT id FROM user_permissions WHERE user_id = ? AND page_key = ?",
			[$user_id, $page_key]
		);

		if ($exists) {
			// update
			$bdd->execute(
				"UPDATE user_permissions 
				 SET can_view = ?, can_edit = ?, can_delete = ?
				 WHERE user_id = ? AND page_key = ?",
				[$can_view, $can_edit, $can_delete, $user_id, $page_key]
			);
		} else {
			// insert
			$bdd->execute(
				"INSERT INTO user_permissions 
				 (user_id, page_key, can_view, can_edit, can_delete)
				 VALUES (?, ?, ?, ?, ?)",
				[$user_id, $page_key, $can_view, $can_edit, $can_delete]
			);
		}
	}

	echo json_encode(['status' => 'success']);

	$bdd->disconnect();
	exit;
}
?>