<?php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

// Enable error logging
ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_reporting(E_ALL);

// Include DB connection
include_once __DIR__ . "/config.php";

// Read POST JSON body
$data = json_decode(file_get_contents("php://input"), true);

if (!$data) {
    echo json_encode(["success" => false, "message" => "Invalid JSON input"]);
    exit;
}

// Required fields
$required = ["name", "module"];
foreach ($required as $field) {
    if (empty($data[$field])) {
        echo json_encode(["success" => false, "message" => "Missing field: $field"]);
        exit;
    }
}

$name = trim($data["name"]);
$module = trim($data["module"]);
$description = isset($data["description"]) ? trim($data["description"]) : "";
$id = isset($data["id"]) ? intval($data["id"]) : 0; // If ID exists, update; else insert

try {
    if ($id > 0) {
        // UPDATE existing permission
        $stmt = $conn->prepare("
            UPDATE permissions 
            SET name = ?, module = ?, description = ?
            WHERE id = ?
        ");
        $stmt->bind_param("sssi", $name, $module, $description, $id);

        if ($stmt->execute()) {
            echo json_encode([
                "success" => true,
                "message" => "Permission updated successfully",
                "id" => $id
            ]);
        } else {
            echo json_encode([
                "success" => false,
                "message" => "Update failed",
                "error" => $stmt->error
            ]);
        }
    } else {
        // INSERT new permission
        $stmt = $conn->prepare("
            INSERT INTO permissions (name, module, description)
            VALUES (?, ?, ?)
        ");
        $stmt->bind_param("sss", $name, $module, $description);

        if ($stmt->execute()) {
            echo json_encode([
                "success" => true,
                "message" => "Permission added successfully",
                "id" => $stmt->insert_id
            ]);
        } else {
            // Handle duplicate permission name
            if (strpos($stmt->error, "Duplicate entry") !== false) {
                echo json_encode([
                    "success" => false,
                    "message" => "Permission with this name already exists"
                ]);
            } else {
                echo json_encode([
                    "success" => false,
                    "message" => "Insert failed",
                    "error" => $stmt->error
                ]);
            }
        }
    }
} catch (Exception $e) {
    echo json_encode([
        "success" => false,
        "message" => "Internal Server Error",
        "error" => $e->getMessage()
    ]);
}
?>
