<?php
require_once '../config/database.php';

$method = $_SERVER['REQUEST_METHOD'];
$input = getInput();

try {
    $db = getDB();

    switch ($method) {
        case 'GET':
            // Get all equipment with stock levels
            $stmt = $db->query("SELECT e.*,
                COALESCE(SUM(CASE WHEN t.type = 'buy' THEN t.quantity ELSE 0 END), 0) as total_bought,
                COALESCE(SUM(CASE WHEN t.type = 'sell' THEN t.quantity ELSE 0 END), 0) as total_sold
                FROM equipment e
                LEFT JOIN equipment_transactions t ON e.id = t.equipment_id
                GROUP BY e.id ORDER BY e.name");
            $items = $stmt->fetchAll();

            foreach ($items as &$item) {
                $item['current_stock'] = $item['total_bought'] - $item['total_sold'];
            }

            sendJson($items);
            break;

        case 'POST':
            if (isset($input['action']) && $input['action'] === 'buy') {
                // Record buy transaction
                $stmt = $db->prepare("INSERT INTO equipment_transactions
                    (equipment_id, type, quantity, unit_price, total_amount, transaction_date, notes)
                    VALUES (?, 'buy', ?, ?, ?, ?, ?)");
                $qty = $input['quantity'] ?? 0;
                $price = $input['unitPrice'] ?? 0;
                $stmt->execute([
                    $input['equipmentId'] ?? 0,
                    $qty,
                    $price,
                    $qty * $price,
                    $input['date'] ?? date('Y-m-d'),
                    $input['notes'] ?? ''
                ]);
                sendJson(['success' => true]);
            }
            elseif (isset($input['action']) && $input['action'] === 'sell') {
                // Record sell transaction
                $stmt = $db->prepare("INSERT INTO equipment_transactions
                    (equipment_id, type, quantity, unit_price, total_amount,
                     buyer_name, student_id, transaction_date, notes)
                    VALUES (?, 'sell', ?, ?, ?, ?, ?, ?, ?)");
                $qty = $input['quantity'] ?? 0;
                $price = $input['unitPrice'] ?? 0;
                $stmt->execute([
                    $input['equipmentId'] ?? 0,
                    $qty,
                    $price,
                    $qty * $price,
                    $input['buyerName'] ?? '',
                    $input['studentId'] ?? null,
                    $input['date'] ?? date('Y-m-d'),
                    $input['notes'] ?? ''
                ]);
                sendJson(['success' => true]);
            }
            else {
                // Add new equipment
                $stmt = $db->prepare("INSERT INTO equipment (name, category, unit_cost, min_stock)
                    VALUES (?, ?, ?, ?)");
                $stmt->execute([
                    $input['name'] ?? '',
                    $input['category'] ?? '',
                    $input['unitCost'] ?? 0,
                    $input['minStock'] ?? 5
                ]);
                sendJson(['success' => true, 'id' => $db->lastInsertId()]);
            }
            break;

        default:
            sendJson(['error' => 'Method not allowed'], 405);
    }
} catch (Exception $e) {
    sendJson(['error' => $e->getMessage()], 500);
}
