<?php
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Insufficient permissions']);
    exit;
}

header('Content-Type: application/json');

try {
    $menu_name = $_POST['menu_name'];
    $menu_url = $_POST['menu_url'] ?? null;
    $menu_icon = $_POST['menu_icon'] ?? null;
    $parent_id = !empty($_POST['parent_id']) ? $_POST['parent_id'] : null;
    $menu_order = $_POST['menu_order'] ?? 0;

    // Check if parent exists if parent_id is provided
    if ($parent_id) {
        $check_sql = "SELECT menu_id FROM menu_items WHERE menu_id = ?";
        $check_stmt = $conn->prepare($check_sql);
        $check_stmt->bind_param('i', $parent_id);
        $check_stmt->execute();
        $result = $check_stmt->get_result();
        
        if ($result->num_rows === 0) {
            throw new Exception('Parent menu item does not exist');
        }
        $check_stmt->close();
    }

    // Insert new menu item
    $insert_sql = "INSERT INTO menu_items (menu_name, menu_url, menu_icon, parent_id, menu_order) 
                   VALUES (?, ?, ?, ?, ?)";
    $insert_stmt = $conn->prepare($insert_sql);
    $insert_stmt->bind_param('sssii', $menu_name, $menu_url, $menu_icon, $parent_id, $menu_order);
    
    if (!$insert_stmt->execute()) {
        throw new Exception('Failed to save menu item');
    }

    $new_menu_id = $insert_stmt->insert_id;
    $insert_stmt->close();

    // Log the activity
    $log_sql = "INSERT INTO activity_log (user_id, action, table_name, record_id, new_values) 
                VALUES (?, 'CREATE', 'menu_items', ?, ?)";
    $log_stmt = $conn->prepare($log_sql);
    $new_values = json_encode([
        'menu_name' => $menu_name,
        'menu_url' => $menu_url,
        'menu_icon' => $menu_icon,
        'parent_id' => $parent_id,
        'menu_order' => $menu_order
    ]);
    $log_stmt->bind_param('iis', $_SESSION['user_id'], $new_menu_id, $new_values);
    $log_stmt->execute();
    $log_stmt->close();

    echo json_encode([
        'success' => true,
        'message' => 'Menu item saved successfully',
        'menu_id' => $new_menu_id
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

$conn->close();
?>