<?php
require_once __DIR__ . '/../includes/config.php';

$createdBy = requireAuth();

$method = $_SERVER['REQUEST_METHOD'];
$id = $_GET['id'] ?? null;

switch ($method) {
    case 'GET':
        if ($id) {
            $stmt = $pdo->prepare('
                SELECT bi.*, b.name as branch_name, c.name as category_name, a.name as created_by_name 
                FROM bills bi 
                LEFT JOIN branches b ON bi.branch_id = b.id 
                LEFT JOIN categories c ON bi.category_id = c.id 
                LEFT JOIN administrators a ON bi.created_by = a.id
                WHERE bi.id = ?
            ');
            $stmt->execute([$id]);
            $bill = $stmt->fetch();
            if ($bill) {
                jsonResponse($bill);
            } else {
                jsonResponse(['error' => 'Boleto não encontrado'], 404);
            }
        } else {
            $startDate = $_GET['startDate'] ?? null;
            $endDate = $_GET['endDate'] ?? null;
            
            $sql = '
                SELECT bi.*, b.name as branch_name, c.name as category_name, a.name as created_by_name 
                FROM bills bi 
                LEFT JOIN branches b ON bi.branch_id = b.id 
                LEFT JOIN categories c ON bi.category_id = c.id
                LEFT JOIN administrators a ON bi.created_by = a.id
            ';
            $params = [];
            
            if ($startDate && $endDate) {
                $sql .= ' WHERE bi.due_date >= ? AND bi.due_date <= ?';
                $params = [$startDate, $endDate];
            }
            
            $sql .= ' ORDER BY bi.due_date ASC, bi.created_at DESC';
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            jsonResponse($stmt->fetchAll());
        }
        break;

    case 'POST':
        $filePath = null;
        
        if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = __DIR__ . '/../uploads/bills/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            
            $fileInfo = pathinfo($_FILES['file']['name']);
            $extension = strtolower($fileInfo['extension']);
            $allowedExtensions = ['pdf', 'jpg', 'jpeg', 'png'];
            
            if (!in_array($extension, $allowedExtensions)) {
                jsonResponse(['error' => 'Tipo de arquivo não permitido. Use PDF, JPG ou PNG.'], 400);
            }
            
            $fileName = 'bill_' . bin2hex(random_bytes(16)) . '.' . $extension;
            $fullPath = $uploadDir . $fileName;
            
            if (move_uploaded_file($_FILES['file']['tmp_name'], $fullPath)) {
                $filePath = 'uploads/bills/' . $fileName;
            }
            
            $data = $_POST;
        } else {
            $data = getJsonInput();
        }
        
        if (isset($data['id']) && !empty($data['id'])) {
            $id = $data['id'];
            
            $stmt = $pdo->prepare('SELECT * FROM bills WHERE id = ?');
            $stmt->execute([$id]);
            $currentBill = $stmt->fetch();
            
            if (!$currentBill) {
                jsonResponse(['error' => 'Boleto não encontrado'], 404);
            }
            
            $sql = 'UPDATE bills SET description = ?, amount = ?, due_date = ?, status = ?, recurrence = ?, branch_id = ?, category_id = ?, notes = ?';
            $params = [
                $data['description'] ?? '',
                $data['amount'] ?? 0,
                $data['dueDate'] ?? date('Y-m-d'),
                $data['status'] ?? 'pending',
                !empty($data['recurrence']) ? $data['recurrence'] : null,
                !empty($data['branchId']) ? $data['branchId'] : null,
                !empty($data['categoryId']) ? $data['categoryId'] : null,
                !empty($data['notes']) ? $data['notes'] : null
            ];
            
            if ($filePath) {
                $sql .= ', file_path = ?';
                $params[] = $filePath;
            }
            
            $sql .= ' WHERE id = ?';
            $params[] = $id;
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            
            $stmt = $pdo->prepare('SELECT * FROM bills WHERE id = ?');
            $stmt->execute([$id]);
            jsonResponse($stmt->fetch());
        } else {
            $id = generateId();
            $stmt = $pdo->prepare('
                INSERT INTO bills (id, description, amount, due_date, status, recurrence, branch_id, category_id, notes, file_path, created_by) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ');
            $stmt->execute([
                $id,
                $data['description'] ?? '',
                $data['amount'] ?? 0,
                $data['dueDate'] ?? date('Y-m-d'),
                $data['status'] ?? 'pending',
                !empty($data['recurrence']) ? $data['recurrence'] : null,
                !empty($data['branchId']) ? $data['branchId'] : null,
                !empty($data['categoryId']) ? $data['categoryId'] : null,
                !empty($data['notes']) ? $data['notes'] : null,
                $filePath,
                $createdBy
            ]);
            
            $stmt = $pdo->prepare('SELECT * FROM bills WHERE id = ?');
            $stmt->execute([$id]);
            jsonResponse($stmt->fetch(), 201);
        }
        break;

    case 'PUT':
        if (!$id) jsonResponse(['error' => 'ID obrigatório'], 400);
        $data = getJsonInput();
        
        $stmt = $pdo->prepare('SELECT * FROM bills WHERE id = ?');
        $stmt->execute([$id]);
        $currentBill = $stmt->fetch();
        
        if (!$currentBill) {
            jsonResponse(['error' => 'Boleto não encontrado'], 404);
        }
        
        $newStatus = $data['status'] ?? 'pending';
        $wasNotPaid = $currentBill['status'] !== 'paid';
        $isNowPaid = $newStatus === 'paid';
        
        $stmt = $pdo->prepare('
            UPDATE bills 
            SET description = ?, amount = ?, due_date = ?, status = ?, recurrence = ?, branch_id = ?, category_id = ?, notes = ?
            WHERE id = ?
        ');
        $stmt->execute([
            $data['description'] ?? '',
            $data['amount'] ?? 0,
            $data['dueDate'] ?? date('Y-m-d'),
            $newStatus,
            !empty($data['recurrence']) ? $data['recurrence'] : null,
            !empty($data['branchId']) ? $data['branchId'] : null,
            !empty($data['categoryId']) ? $data['categoryId'] : null,
            !empty($data['notes']) ? $data['notes'] : null,
            $id
        ]);
        
        $stmt = $pdo->prepare('SELECT * FROM bills WHERE id = ?');
        $stmt->execute([$id]);
        $bill = $stmt->fetch();
        
        if ($wasNotPaid && $isNowPaid && $bill) {
            $transactionId = generateId();
            $stmt = $pdo->prepare('
                INSERT INTO transactions (id, type, description, amount, transaction_date, payment_method, branch_id, category_id, notes, created_by)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ');
            $stmt->execute([
                $transactionId,
                'expense',
                'Boleto: ' . $bill['description'],
                $bill['amount'],
                date('Y-m-d'),
                'boleto',
                $bill['branch_id'],
                $bill['category_id'],
                'Pagamento de boleto - Vencimento: ' . $bill['due_date'],
                $createdBy
            ]);
        }
        
        if ($bill) {
            jsonResponse($bill);
        } else {
            jsonResponse(['error' => 'Boleto não encontrado'], 404);
        }
        break;

    case 'DELETE':
        if (!$id) jsonResponse(['error' => 'ID obrigatório'], 400);
        
        $stmt = $pdo->prepare('SELECT file_path FROM bills WHERE id = ?');
        $stmt->execute([$id]);
        $bill = $stmt->fetch();
        
        if ($bill && $bill['file_path']) {
            $filePath = __DIR__ . '/../' . $bill['file_path'];
            if (file_exists($filePath)) {
                unlink($filePath);
            }
        }
        
        $stmt = $pdo->prepare('DELETE FROM bills WHERE id = ?');
        $stmt->execute([$id]);
        if ($stmt->rowCount() > 0) {
            jsonResponse(['success' => true]);
        } else {
            jsonResponse(['error' => 'Boleto não encontrado'], 404);
        }
        break;

    default:
        jsonResponse(['error' => 'Método não permitido'], 405);
}
