<?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;

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

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

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

    $period = $_GET['period'] ?? 'month';
    $date_start = $_GET['date_start'] ?? null;
    $date_end = $_GET['date_end'] ?? null;

    if ($date_start && $date_end) {
        $where[] = 'ec.consumption_date >= ?';
        $params[] = $date_start;
        $where[] = 'ec.consumption_date <= ?';
        $params[] = $date_end;
    } else {
        $today = date('Y-m-d');
        switch ($period) {
            case 'day':
                $where[] = 'ec.consumption_date = ?';
                $params[] = $today;
                break;
            case 'week':
                $weekStart = date('Y-m-d', strtotime('monday this week'));
                $where[] = 'ec.consumption_date >= ?';
                $params[] = $weekStart;
                $where[] = 'ec.consumption_date <= ?';
                $params[] = $today;
                break;
            case 'biweekly':
                $day = (int)date('d');
                if ($day <= 15) {
                    $start = date('Y-m-01');
                    $end = date('Y-m-15');
                } else {
                    $start = date('Y-m-16');
                    $end = date('Y-m-t');
                }
                $where[] = 'ec.consumption_date >= ?';
                $params[] = $start;
                $where[] = 'ec.consumption_date <= ?';
                $params[] = $end;
                break;
            case 'month':
                $where[] = 'ec.consumption_date >= ?';
                $params[] = date('Y-m-01');
                $where[] = 'ec.consumption_date <= ?';
                $params[] = date('Y-m-t');
                break;
            case 'bimonthly':
                $month = (int)date('m');
                $startMonth = $month % 2 === 0 ? $month - 1 : $month;
                $where[] = 'ec.consumption_date >= ?';
                $params[] = date('Y-' . str_pad($startMonth, 2, '0', STR_PAD_LEFT) . '-01');
                $endMonth = $startMonth + 1;
                $where[] = 'ec.consumption_date <= ?';
                $params[] = date('Y-' . str_pad($endMonth, 2, '0', STR_PAD_LEFT) . '-' . date('t', mktime(0, 0, 0, $endMonth, 1)));
                break;
            case 'semester':
                $month = (int)date('m');
                $startMonth = $month <= 6 ? 1 : 7;
                $endMonth = $month <= 6 ? 6 : 12;
                $where[] = 'ec.consumption_date >= ?';
                $params[] = date('Y-' . str_pad($startMonth, 2, '0', STR_PAD_LEFT) . '-01');
                $where[] = 'ec.consumption_date <= ?';
                $params[] = date('Y-' . str_pad($endMonth, 2, '0', STR_PAD_LEFT) . '-' . date('t', mktime(0, 0, 0, $endMonth, 1)));
                break;
            case 'year':
                $where[] = 'ec.consumption_date >= ?';
                $params[] = date('Y-01-01');
                $where[] = 'ec.consumption_date <= ?';
                $params[] = date('Y-12-31');
                break;
            default:
                $where[] = 'ec.consumption_date >= ?';
                $params[] = date('Y-m-01');
                $where[] = 'ec.consumption_date <= ?';
                $params[] = date('Y-m-t');
        }
    }

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

    $sql = "SELECT ec.*, e.name as employee_name, b.name as branch_name
            FROM employee_consumptions ec
            JOIN employees e ON ec.employee_id = e.id
            LEFT JOIN branches b ON ec.branch_id = b.id
            $whereClause
            ORDER BY ec.consumption_date DESC, e.name ASC";

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

    $grouped = [];
    foreach ($consumptions as $c) {
        $empId = $c['employee_id'];
        if (!isset($grouped[$empId])) {
            $grouped[$empId] = [
                'employee_id' => $empId,
                'employee_name' => $c['employee_name'],
                'items' => [],
                'total' => 0
            ];
        }
        $itemTotal = (float)$c['item_value'] * (float)$c['quantity'];
        $grouped[$empId]['items'][] = $c;
        $grouped[$empId]['total'] += $itemTotal;
    }

    $result = array_values($grouped);

    $totalStmt = $pdo->prepare("SELECT COALESCE(SUM(ec.item_value * ec.quantity), 0) as grand_total FROM employee_consumptions ec $whereClause");
    $totalStmt->execute($params);
    $grandTotal = $totalStmt->fetch()['grand_total'];

    jsonResponse([
        'consumptions' => $consumptions,
        'grouped' => $result,
        'grand_total' => (float)$grandTotal
    ]);
}

function handlePost($admin) {
    global $pdo;

    $data = getJsonInput();

    if (empty($data['employee_id']) || empty($data['item_name']) || empty($data['consumption_date'])) {
        jsonResponse(['error' => 'Funcionário, item e data são obrigatórios'], 400);
    }

    $id = generateId();

    $stmt = $pdo->prepare('INSERT INTO employee_consumptions (id, employee_id, stock_item_id, item_name, item_value, quantity, consumption_date, branch_id, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
    $stmt->execute([
        $id,
        $data['employee_id'],
        $data['stock_item_id'] ?? null,
        $data['item_name'],
        $data['item_value'] ?? 0,
        $data['quantity'] ?? 1,
        $data['consumption_date'],
        $data['branch_id'] ?? null,
        $admin
    ]);

    jsonResponse(['success' => true, 'id' => $id, 'message' => 'Consumo registrado 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 = ['employee_id', 'stock_item_id', 'item_name', 'item_value', 'quantity', 'consumption_date', '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 employee_consumptions SET ' . implode(', ', $fields) . ' WHERE id = ?';
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);

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

function handleDelete() {
    global $pdo;

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

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

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