<?php
/**
 * AJAX Handler: Toggle Menu Item Status
 * File: ajax/toggle_menu_status.php
 * 
 * Activates or deactivates menu items
 */

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

// Start session and check authentication
session_start();

if (!isset($_SESSION['user_id'])) {
    echo json_encode([
        'success' => false,
        'message' => 'Unauthorized access'
    ]);
    exit();
}

// Include database connection
require_once '../layouts/dbconn.php';

try {
    // Get POST data
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($data['menu_id']) || !isset($data['status'])) {
        throw new Exception('Missing required parameters');
    }
    
    $menu_id = (int)$data['menu_id'];
    $status = $data['status'] ? 1 : 0;
    $user_id = $_SESSION['user_id'];
    
    // Begin transaction
    $conn->begin_transaction();
    
    // Update menu item status
    $update_sql = "UPDATE menu_items 
                   SET is_active = ?, 
                       updated_at = CURRENT_TIMESTAMP 
                   WHERE menu_id = ?";
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param("ii", $status, $menu_id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to update menu status');
    }
    
    // Get menu item details for logging
    $menu_sql = "SELECT menu_name, menu_url FROM menu_items WHERE menu_id = ?";
    $menu_stmt = $conn->prepare($menu_sql);
    $menu_stmt->bind_param("i", $menu_id);
    $menu_stmt->execute();
    $menu_result = $menu_stmt->get_result();
    $menu_item = $menu_result->fetch_assoc();
    
    // Log activity
    $action = $status ? 'activated' : 'deactivated';
    $log_description = "Menu item '{$menu_item['menu_name']}' ({$menu_item['menu_url']}) was {$action}";
    
    $log_sql = "INSERT INTO activity_log (user_id, action_type, description, ip_address, user_agent) 
                VALUES (?, 'menu_status_change', ?, ?, ?)";
    $log_stmt = $conn->prepare($log_sql);
    $log_stmt->bind_param("isss", 
        $user_id, 
        $log_description,
        $_SERVER['REMOTE_ADDR'],
        $_SERVER['HTTP_USER_AGENT']
    );
    $log_stmt->execute();
    
    // Commit transaction
    $conn->commit();
    
    // Return success response
    echo json_encode([
        'success' => true,
        'message' => "Menu item {$action} successfully",
        'menu_id' => $menu_id,
        'new_status' => $status,
        'menu_name' => $menu_item['menu_name']
    ]);
    
} catch (Exception $e) {
    // Rollback on error
    if ($conn) {
        $conn->rollback();
    }
    
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

// Close connections
if (isset($stmt)) $stmt->close();
if (isset($menu_stmt)) $menu_stmt->close();
if (isset($log_stmt)) $log_stmt->close();
if (isset($conn)) $conn->close();
?>