<?php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit();
}
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'طريقة غير مسموحة']);
    exit();
}

$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['id']) || !isset($input['status'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'بيانات ناقصة']);
    exit();
}

$id = (int)$input['id'];
$status = $input['status'] === 'true' ? 1 : 0;

try {
    $db = new Database();
    $conn = $db->getConnection();
    
    $stmt = $conn->prepare("UPDATE antibiotics SET is_active = ? WHERE id = ?");
    $stmt->execute([$status, $id]);
    
    if ($stmt->rowCount() > 0) {
        logActivity($conn, $_SESSION['user_id'], 'تغيير حالة المضاد الحيوي', 'antibiotics', $id);
        echo json_encode(['success' => true, 'message' => 'تم تحديث الحالة بنجاح']);
    } else {
        echo json_encode(['success' => false, 'message' => 'لم يتم العثور على المضاد الحيوي']);
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'حدث خطأ في الخادم']);
    error_log("Toggle antibiotic status error: " . $e->getMessage());
}
?>
