<?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 t.*, b.name as branch_name, c.name as category_name, p.name as partner_name, a.name as created_by_name 
                FROM transactions t 
                LEFT JOIN branches b ON t.branch_id = b.id 
                LEFT JOIN categories c ON t.category_id = c.id 
                LEFT JOIN partners p ON t.partner_id = p.id 
                LEFT JOIN administrators a ON t.created_by = a.id
                WHERE t.id = ?
            ');
            $stmt->execute([$id]);
            $transaction = $stmt->fetch();
            if ($transaction) {
                jsonResponse($transaction);
            } else {
                jsonResponse(['error' => 'Lançamento não encontrado'], 404);
            }
        } else {
            $startDate = $_GET['startDate'] ?? null;
            $endDate = $_GET['endDate'] ?? null;
            
            $sql = '
                SELECT t.*, b.name as branch_name, c.name as category_name, p.name as partner_name, a.name as created_by_name 
                FROM transactions t 
                LEFT JOIN branches b ON t.branch_id = b.id 
                LEFT JOIN categories c ON t.category_id = c.id 
                LEFT JOIN partners p ON t.partner_id = p.id
                LEFT JOIN administrators a ON t.created_by = a.id
            ';
            $params = [];
            
            if ($startDate && $endDate) {
                $sql .= ' WHERE t.transaction_date >= ? AND t.transaction_date <= ?';
                $params = [$startDate, $endDate];
            }
            
            $sql .= ' ORDER BY t.transaction_date DESC, t.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/transactions/';
            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 = 'tx_' . bin2hex(random_bytes(16)) . '.' . $extension;
            $fullPath = $uploadDir . $fileName;
            
            if (move_uploaded_file($_FILES['file']['tmp_name'], $fullPath)) {
                $filePath = 'uploads/transactions/' . $fileName;
            }
            
            $data = $_POST;
        } else {
            $data = getJsonInput();
        }
        
        if (isset($data['id']) && !empty($data['id'])) {
            $id = $data['id'];
            $updateFields = [
                'type' => $data['type'] ?? 'expense',
                'description' => $data['description'] ?? '',
                'amount' => $data['amount'] ?? 0,
                'transaction_date' => $data['date'] ?? date('Y-m-d'),
                'payment_method' => !empty($data['paymentMethod']) ? $data['paymentMethod'] : null,
                'branch_id' => !empty($data['branchId']) ? $data['branchId'] : null,
                'category_id' => !empty($data['categoryId']) ? $data['categoryId'] : null,
                'partner_id' => !empty($data['partnerId']) ? $data['partnerId'] : null,
                'notes' => !empty($data['notes']) ? $data['notes'] : null
            ];
            
            $sql = 'UPDATE transactions SET type = ?, description = ?, amount = ?, transaction_date = ?, payment_method = ?, branch_id = ?, category_id = ?, partner_id = ?, notes = ?';
            $params = array_values($updateFields);
            
            if ($filePath) {
                $sql .= ', file_path = ?';
                $params[] = $filePath;
            }
            
            $sql .= ' WHERE id = ?';
            $params[] = $id;
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            
            $stmt = $pdo->prepare('SELECT * FROM transactions WHERE id = ?');
            $stmt->execute([$id]);
            jsonResponse($stmt->fetch());
        } else {
            $id = generateId();
            $stmt = $pdo->prepare('
                INSERT INTO transactions (id, type, description, amount, transaction_date, due_date, payment_method, branch_id, category_id, partner_id, status, notes, file_path, created_by) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ');
            $stmt->execute([
                $id,
                $data['type'] ?? 'expense',
                $data['description'] ?? '',
                $data['amount'] ?? 0,
                $data['date'] ?? date('Y-m-d'),
                $data['dueDate'] ?? null,
                !empty($data['paymentMethod']) ? $data['paymentMethod'] : null,
                !empty($data['branchId']) ? $data['branchId'] : null,
                !empty($data['categoryId']) ? $data['categoryId'] : null,
                !empty($data['partnerId']) ? $data['partnerId'] : null,
                $data['status'] ?? 'completed',
                !empty($data['notes']) ? $data['notes'] : null,
                $filePath,
                $createdBy
            ]);
            
            $stmt = $pdo->prepare('SELECT * FROM transactions 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('
            UPDATE transactions 
            SET type = ?, description = ?, amount = ?, transaction_date = ?, due_date = ?, payment_method = ?, branch_id = ?, category_id = ?, partner_id = ?, status = ?, notes = ?
            WHERE id = ?
        ');
        $stmt->execute([
            $data['type'] ?? 'expense',
            $data['description'] ?? '',
            $data['amount'] ?? 0,
            $data['date'] ?? date('Y-m-d'),
            $data['dueDate'] ?? null,
            !empty($data['paymentMethod']) ? $data['paymentMethod'] : null,
            !empty($data['branchId']) ? $data['branchId'] : null,
            !empty($data['categoryId']) ? $data['categoryId'] : null,
            !empty($data['partnerId']) ? $data['partnerId'] : null,
            $data['status'] ?? 'completed',
            !empty($data['notes']) ? $data['notes'] : null,
            $id
        ]);
        
        $stmt = $pdo->prepare('SELECT * FROM transactions WHERE id = ?');
        $stmt->execute([$id]);
        $transaction = $stmt->fetch();
        if ($transaction) {
            jsonResponse($transaction);
        } else {
            jsonResponse(['error' => 'Lançamento não encontrado'], 404);
        }
        break;

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

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