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

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

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

try {
    // Validate required fields
    $required_fields = ['menu_id', 'menu_name'];
    foreach ($required_fields as $field) {
        if (!isset($_POST[$field]) || empty(trim($_POST[$field]))) {
            throw new Exception("Missing required field: $field");
        }
    }

    $menu_id = intval($_POST['menu_id']);
    $menu_name = trim($_POST['menu_name']);
    $menu_url = isset($_POST['menu_url']) ? trim($_POST['menu_url']) : null;
    $menu_icon = isset($_POST['menu_icon']) ? trim($_POST['menu_icon']) : null;
    $parent_id = isset($_POST['parent_id']) && !empty($_POST['parent_id']) ? intval($_POST['parent_id']) : null;
    $menu_order = isset($_POST['menu_order']) ? intval($_POST['menu_order']) : 0;

    // Validate that parent_id is not the same as menu_id (prevent self-reference)
    if ($parent_id === $menu_id) {
        throw new Exception('A menu item cannot be its own parent');
    }

    // Check if menu exists
    $check_sql = "SELECT menu_id FROM menu_items WHERE menu_id = ?";
    $check_stmt = $conn->prepare($check_sql);
    if (!$check_stmt) {
        throw new Exception("Failed to prepare check statement: " . $conn->error);
    }
    
    $check_stmt->bind_param('i', $menu_id);
    $check_stmt->execute();
    $check_result = $check_stmt->get_result();
    
    if ($check_result->num_rows === 0) {
        throw new Exception('Menu item not found');
    }
    $check_stmt->close();

    // If parent_id is provided, validate it exists
    if ($parent_id !== null) {
        $parent_check_sql = "SELECT menu_id FROM menu_items WHERE menu_id = ? AND parent_id IS NULL";
        $parent_stmt = $conn->prepare($parent_check_sql);
        if (!$parent_stmt) {
            throw new Exception("Failed to prepare parent check statement: " . $conn->error);
        }
        
        $parent_stmt->bind_param('i', $parent_id);
        $parent_stmt->execute();
        $parent_result = $parent_stmt->get_result();
        
        if ($parent_result->num_rows === 0) {
            throw new Exception('Selected parent menu does not exist or is not a top-level menu');
        }
        $parent_stmt->close();
    }

    // Begin transaction
    $conn->autocommit(FALSE);

    try {
        // Update menu item
        $sql = "UPDATE menu_items 
                SET menu_name = ?, 
                    menu_url = ?, 
                    menu_icon = ?, 
                    parent_id = ?, 
                    menu_order = ?
                WHERE menu_id = ?";
        
        $stmt = $conn->prepare($sql);
        if (!$stmt) {
            throw new Exception("Failed to prepare update statement: " . $conn->error);
        }
        
        $stmt->bind_param('ssssii', $menu_name, $menu_url, $menu_icon, $parent_id, $menu_order, $menu_id);
        
        if (!$stmt->execute()) {
            throw new Exception("Failed to update menu: " . $stmt->error);
        }

        if ($stmt->affected_rows === 0) {
            throw new Exception('No changes were made to the menu item');
        }

        // Log the activity
        $activity_sql = "INSERT INTO activity_log (
            user_id, 
            action, 
            table_name, 
            record_id, 
            new_values, 
            ip_address, 
            user_agent, 
            action_date
        ) VALUES (?, 'UPDATE', 'menu_items', ?, ?, ?, ?, NOW())";

        $activity_stmt = $conn->prepare($activity_sql);
        if ($activity_stmt) {
            $new_values = json_encode([
                'menu_name' => $menu_name,
                'menu_url' => $menu_url,
                'menu_icon' => $menu_icon,
                'parent_id' => $parent_id,
                'menu_order' => $menu_order
            ]);
            
            $ip_address = $_SERVER['REMOTE_ADDR'] ?? '';
            $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
            
            $activity_stmt->bind_param('sssss', 
                $_SESSION['user_id'], 
                $menu_id, 
                $new_values, 
                $ip_address, 
                $user_agent
            );
            
            $activity_stmt->execute();
            $activity_stmt->close();
        }

        // Commit transaction
        $conn->commit();

        echo json_encode([
            'success' => true,
            'message' => 'Menu item updated successfully'
        ]);

    } catch (Exception $e) {
        // Rollback transaction on error
        $conn->rollback();
        throw $e;
    }

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
} finally {
    // Reset autocommit
    if (isset($conn)) {
        $conn->autocommit(TRUE);
    }
    
    if (isset($stmt)) {
        $stmt->close();
    }
    
    $conn->close();
}
?>