<?php
header('Content-Type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', 0);

try {
    require_once __DIR__ . '/../includes/config.php';
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Erro de configuração: ' . $e->getMessage()]);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'OPTIONS') {
    http_response_code(200);
    exit;
}

$admin = requireAuth();

try {
    switch ($method) {
        case 'GET':
            handleGet();
            break;
        case 'POST':
            handlePost($admin);
            break;
        case 'DELETE':
            handleDelete();
            break;
        default:
            http_response_code(405);
            echo json_encode(['error' => 'Método não permitido']);
    }
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Erro no banco de dados: ' . $e->getMessage()]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Erro: ' . $e->getMessage()]);
}

function handleGet() {
    global $pdo;

    $where = [];
    $params = [];

    $stock_item_id = $_GET['stock_item_id'] ?? null;
    if ($stock_item_id) {
        $where[] = 'sen.stock_item_id = ?';
        $params[] = $stock_item_id;
    }

    $branch_id = $_GET['branch_id'] ?? null;
    if ($branch_id) {
        $where[] = 'si.branch_id = ?';
        $params[] = $branch_id;
    }

    $category = $_GET['category'] ?? null;
    if ($category) {
        $where[] = 'si.category = ?';
        $params[] = $category;
    }

    $item_type = $_GET['item_type'] ?? null;
    if ($item_type) {
        $where[] = 'si.item_type = ?';
        $params[] = $item_type;
    }

    $search = $_GET['search'] ?? null;
    if ($search) {
        $where[] = 'LOWER(si.name) LIKE LOWER(?)';
        $params[] = "%$search%";
    }

    $date_start = $_GET['date_start'] ?? null;
    if ($date_start) {
        $where[] = 'sen.entry_date >= ?';
        $params[] = $date_start;
    }

    $date_end = $_GET['date_end'] ?? null;
    if ($date_end) {
        $where[] = 'sen.entry_date <= ?';
        $params[] = $date_end;
    }

    $whereClause = count($where) > 0 ? 'WHERE ' . implode(' AND ', $where) : '';

    $sql = "SELECT sen.*, si.name as item_name, si.item_type, si.category, si.purchase_price, b.name as branch_name
            FROM stock_entries sen
            JOIN stock_items si ON sen.stock_item_id = si.id
            LEFT JOIN branches b ON si.branch_id = b.id
            $whereClause
            ORDER BY sen.entry_date DESC, sen.created_at DESC";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $entries = $stmt->fetchAll();

    jsonResponse(['entries' => $entries]);
}

function handlePost($admin) {
    global $pdo;

    $data = getJsonInput();

    if (empty($data['stock_item_id']) || empty($data['quantity']) || empty($data['entry_date'])) {
        jsonResponse(['error' => 'Item, quantidade e data são obrigatórios'], 400);
    }

    $itemStmt = $pdo->prepare('SELECT id FROM stock_items WHERE id = ?');
    $itemStmt->execute([$data['stock_item_id']]);
    $item = $itemStmt->fetch();

    if (!$item) {
        jsonResponse(['error' => 'Item não encontrado'], 404);
    }

    $pdo->beginTransaction();
    try {
        $id = generateId();
        $stmt = $pdo->prepare('INSERT INTO stock_entries (id, stock_item_id, quantity, entry_date, notes, created_by) VALUES (?, ?, ?, ?, ?, ?)');
        $stmt->execute([
            $id,
            $data['stock_item_id'],
            $data['quantity'],
            $data['entry_date'],
            $data['notes'] ?? null,
            $admin
        ]);

        $updateStmt = $pdo->prepare('UPDATE stock_items SET quantity = quantity + ? WHERE id = ?');
        $updateStmt->execute([$data['quantity'], $data['stock_item_id']]);

        $pdo->commit();
        jsonResponse(['success' => true, 'id' => $id, 'message' => 'Entrada registrada com sucesso']);
    } catch (Exception $e) {
        $pdo->rollBack();
        throw $e;
    }
}

function handleDelete() {
    global $pdo;

    $id = $_GET['id'] ?? null;
    if (!$id) {
        jsonResponse(['error' => 'ID é obrigatório'], 400);
    }

    $entryStmt = $pdo->prepare('SELECT stock_item_id, quantity FROM stock_entries WHERE id = ?');
    $entryStmt->execute([$id]);
    $entry = $entryStmt->fetch();

    if (!$entry) {
        jsonResponse(['error' => 'Entrada não encontrada'], 404);
    }

    $pdo->beginTransaction();
    try {
        $updateStmt = $pdo->prepare('UPDATE stock_items SET quantity = quantity - ? WHERE id = ?');
        $updateStmt->execute([$entry['quantity'], $entry['stock_item_id']]);

        $deleteStmt = $pdo->prepare('DELETE FROM stock_entries WHERE id = ?');
        $deleteStmt->execute([$id]);

        $pdo->commit();
        jsonResponse(['success' => true, 'message' => 'Entrada excluída e estoque ajustado']);
    } catch (Exception $e) {
        $pdo->rollBack();
        throw $e;
    }
}
