<?php
/**
 * Log Equipment Usage AJAX Endpoint
 * Records equipment usage by audiologists
 */

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

require_once '../layouts/session.php';
require_once '../layouts/dbconn.php';

$response = ['success' => false, 'message' => ''];

// Check authentication
if (!isset($_SESSION['user_id']) || $_SESSION['role_code'] != 'AUDIOLOGIST') {
    $response['message'] = 'Unauthorized access.';
    echo json_encode($response);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] != 'POST') {
    $response['message'] = 'Invalid request method.';
    echo json_encode($response);
    exit();
}

// Get input
$equipment_id = isset($_POST['equipment_id']) ? intval($_POST['equipment_id']) : 0;
$purpose = isset($_POST['purpose']) ? trim($_POST['purpose']) : '';
$duration = isset($_POST['duration']) ? intval($_POST['duration']) : 0;
$user_id = $_SESSION['user_id'];

if ($equipment_id <= 0) {
    $response['message'] = 'Invalid equipment ID.';
    echo json_encode($response);
    exit();
}

$conn->begin_transaction();

try {
    // Verify equipment exists and is operational
    $verify_sql = "SELECT equipment_id, equipment_name, status FROM equipment_logs WHERE equipment_id = ?";
    $stmt = $conn->prepare($verify_sql);
    $stmt->bind_param("i", $equipment_id);
    $stmt->execute();
    $equipment = $stmt->get_result()->fetch_assoc();
    
    if (!$equipment) {
        throw new Exception('Equipment not found.');
    }
    
    // Check if equipment_usage_logs table exists, if not, create record in activity_log instead
    $table_check = $conn->query("SHOW TABLES LIKE 'equipment_usage_logs'");
    
    if ($table_check->num_rows > 0) {
        // Insert into equipment_usage_logs
        $insert_sql = "INSERT INTO equipment_usage_logs 
                      (equipment_id, used_by, purpose, duration_minutes, used_at, created_at)
                      VALUES (?, ?, ?, ?, NOW(), NOW())";
        
        $stmt = $conn->prepare($insert_sql);
        $stmt->bind_param("iisi", $equipment_id, $user_id, $purpose, $duration);
        
        if (!$stmt->execute()) {
            throw new Exception('Failed to log equipment usage.');
        }
    }
    
    // Log in activity_log
    $activity_sql = "INSERT INTO activity_log 
                    (user_id, action, module, record_id, record_type, new_values, ip_address, logged_at)
                    VALUES (?, 'EQUIPMENT_USE', 'AUDIOLOGY', ?, 'EQUIPMENT', ?, ?, NOW())";
    
    $new_values = json_encode([
        'equipment_id' => $equipment_id,
        'equipment_name' => $equipment['equipment_name'],
        'purpose' => $purpose,
        'duration_minutes' => $duration,
        'used_by' => $_SESSION['full_name'] ?? 'Audiologist'
    ]);
    
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
    
    $stmt = $conn->prepare($activity_sql);
    $stmt->bind_param("iiss", $user_id, $equipment_id, $new_values, $ip_address);
    $stmt->execute();
    
    $conn->commit();
    
    $response['success'] = true;
    $response['message'] = 'Equipment usage logged successfully.';
    
} catch (Exception $e) {
    $conn->rollback();
    $response['message'] = $e->getMessage();
    error_log("Error logging equipment usage: " . $e->getMessage());
}

$conn->close();
echo json_encode($response);
?>