<?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 {
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input || !isset($input['menu_id']) || !isset($input['status'])) {
        throw new Exception('Invalid input data');
    }

    $menu_id = intval($input['menu_id']);
    $status = $input['status'] ? 1 : 0;

    // Check if menu exists
    $check_sql = "SELECT menu_id, menu_name 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');
    }
    
    $menu_data = $check_result->fetch_assoc();
    $check_stmt->close();

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

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

        // If disabling a parent menu, also disable its children
        if ($status === 0) {
            $child_sql = "UPDATE menu_items SET is_active = 0 WHERE parent_id = ?";
            $child_stmt = $conn->prepare($child_sql);
            if ($child_stmt) {
                $child_stmt->bind_param('i', $menu_id);
                $child_stmt->execute();
                $child_stmt->close();
            }
        }

        // 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([
                'is_active' => $status,
                'menu_name' => $menu_data['menu_name']
            ]);
            
            $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 status 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();
}
?>