<?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 'PUT':
            handlePut();
            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;

    $id = $_GET['id'] ?? null;

    if ($id) {
        $stmt = $pdo->prepare('SELECT si.*, b.name as branch_name FROM stock_items si LEFT JOIN branches b ON si.branch_id = b.id WHERE si.id = ?');
        $stmt->execute([$id]);
        $item = $stmt->fetch();
        if (!$item) {
            jsonResponse(['error' => 'Item não encontrado'], 404);
        }
        jsonResponse($item);
    }

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

    $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%";
    }

    $low_stock = $_GET['low_stock'] ?? null;
    if ($low_stock) {
        $where[] = 'si.quantity <= ?';
        $params[] = (float)$low_stock;
    }

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

    $date_end = $_GET['date_end'] ?? null;
    if ($date_end) {
        $where[] = 'si.created_at <= ?';
        $params[] = $date_end . ' 23:59:59';
    }

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

    $sql = "SELECT si.*, b.name as branch_name 
            FROM stock_items si 
            LEFT JOIN branches b ON si.branch_id = b.id 
            $whereClause 
            ORDER BY si.name ASC";

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

    $catStmt = $pdo->query("SELECT DISTINCT category FROM stock_items WHERE category IS NOT NULL AND category != '' ORDER BY category");
    $categories = $catStmt->fetchAll(PDO::FETCH_COLUMN);

    jsonResponse(['items' => $items, 'categories' => $categories]);
}

function handlePost($admin) {
    global $pdo;

    $data = getJsonInput();

    if (empty($data['name'])) {
        jsonResponse(['error' => 'Nome é obrigatório'], 400);
    }

    $id = generateId();

    $stmt = $pdo->prepare('INSERT INTO stock_items (id, name, purchase_price, sale_price, quantity, min_quantity, category, item_type, branch_id, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
    $stmt->execute([
        $id,
        $data['name'],
        $data['purchase_price'] ?? 0,
        $data['sale_price'] ?? 0,
        $data['quantity'] ?? 0,
        $data['min_quantity'] ?? 0,
        $data['category'] ?? null,
        $data['item_type'] ?? 'unidade',
        $data['branch_id'] ?? null,
        $admin
    ]);

    jsonResponse(['success' => true, 'id' => $id, 'message' => 'Item cadastrado com sucesso']);
}

function handlePut() {
    global $pdo;

    $data = getJsonInput();
    $id = $data['id'] ?? $_GET['id'] ?? null;

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

    $fields = [];
    $params = [];

    $updatable = ['name', 'purchase_price', 'sale_price', 'quantity', 'min_quantity', 'category', 'item_type', 'branch_id'];
    foreach ($updatable as $field) {
        if (isset($data[$field])) {
            $fields[] = "$field = ?";
            $params[] = $data[$field];
        }
    }

    if (empty($fields)) {
        jsonResponse(['error' => 'Nenhum campo para atualizar'], 400);
    }

    $params[] = $id;
    $sql = 'UPDATE stock_items SET ' . implode(', ', $fields) . ' WHERE id = ?';
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);

    jsonResponse(['success' => true, 'message' => 'Item atualizado com sucesso']);
}

function handleDelete() {
    global $pdo;

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

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

    jsonResponse(['success' => true, 'message' => 'Item excluído com sucesso']);
}
