<?php
/**
 * ============================================================================
 * farm/transactions.php - Financial Transactions
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

if (getUserType() !== 'farmer') {
    redirect('/dashboard/', 'Only farmers can access transactions', 'error');
}

$pageTitle = 'Transactions';
$userId = getUserId();

// Get database connection
$database = new Database();
$db = $database->getConnection();

// Get filters
$filters = [
    'type' => $_GET['type'] ?? '',
    'start_date' => $_GET['start_date'] ?? date('Y-m-01'), // First day of current month
    'end_date' => $_GET['end_date'] ?? date('Y-m-d'),
    'limit' => 100
];

// Get transactions
$transactionClass = new \App\Transaction($db);
$transactions = $transactionClass->getUserTransactions($userId, $filters);

// Get summary
$summary = $transactionClass->getSummary($userId, $filters['start_date'], $filters['end_date']);

// Get enterprises for filter
$sql = "SELECT DISTINCT e.id, e.enterprise_name, e.enterprise_type 
        FROM enterprises e
        JOIN farms f ON e.farm_id = f.id
        WHERE f.user_id = ?
        ORDER BY e.enterprise_name";
$stmt = $db->prepare($sql);
$stmt->execute([$userId]);
$enterprises = $stmt->fetchAll(PDO::FETCH_ASSOC);

include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>

<div class="container-fluid py-4">
    <!-- Header -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
                <div>
                    <h2 class="mb-1">
                        <i class="bi bi-wallet2 text-info"></i> Financial Transactions
                    </h2>
                    <p class="text-muted mb-0">Track your farm income and expenses</p>
                </div>
                <a href="<?php echo APP_URL; ?>/farm/add-transaction.php" class="btn btn-success">
                    <i class="bi bi-plus-circle"></i> Add Transaction
                </a>
            </div>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="row mb-4">
        <div class="col-md-3 mb-3">
            <div class="card border-0 shadow-sm bg-success text-white">
                <div class="card-body">
                    <h6 class="mb-2 opacity-75">Total Income</h6>
                    <h3 class="mb-0"><?php echo formatCurrency($summary['total_income'] ?? 0); ?></h3>
                    <small class="opacity-75"><?php echo $summary['income_count']; ?> transactions</small>
                </div>
            </div>
        </div>
        
        <div class="col-md-3 mb-3">
            <div class="card border-0 shadow-sm bg-danger text-white">
                <div class="card-body">
                    <h6 class="mb-2 opacity-75">Total Expenses</h6>
                    <h3 class="mb-0"><?php echo formatCurrency($summary['total_expenses'] ?? 0); ?></h3>
                    <small class="opacity-75"><?php echo $summary['expense_count']; ?> transactions</small>
                </div>
            </div>
        </div>
        
        <div class="col-md-3 mb-3">
            <div class="card border-0 shadow-sm <?php echo ($summary['net_profit'] ?? 0) >= 0 ? 'bg-primary' : 'bg-warning'; ?> text-white">
                <div class="card-body">
                    <h6 class="mb-2 opacity-75">Net Profit/Loss</h6>
                    <h3 class="mb-0"><?php echo formatCurrency(abs($summary['net_profit'] ?? 0)); ?></h3>
                    <small class="opacity-75"><?php echo ($summary['net_profit'] ?? 0) >= 0 ? 'Profit' : 'Loss'; ?></small>
                </div>
            </div>
        </div>
        
        <div class="col-md-3 mb-3">
            <div class="card border-0 shadow-sm bg-info text-white">
                <div class="card-body">
                    <h6 class="mb-2 opacity-75">Period</h6>
                    <div class="small"><?php echo formatDate($filters['start_date']); ?></div>
                    <div class="small">to <?php echo formatDate($filters['end_date']); ?></div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <form method="GET" class="row g-3">
                        <div class="col-md-3">
                            <label class="form-label">Transaction Type</label>
                            <select class="form-select" name="type">
                                <option value="">All Types</option>
                                <option value="income" <?php echo $filters['type'] === 'income' ? 'selected' : ''; ?>>
                                    Income Only
                                </option>
                                <option value="expense" <?php echo $filters['type'] === 'expense' ? 'selected' : ''; ?>>
                                    Expenses Only
                                </option>
                            </select>
                        </div>
                        
                        <div class="col-md-3">
                            <label class="form-label">Start Date</label>
                            <input type="date" class="form-control" name="start_date" 
                                   value="<?php echo $filters['start_date']; ?>">
                        </div>
                        
                        <div class="col-md-3">
                            <label class="form-label">End Date</label>
                            <input type="date" class="form-control" name="end_date" 
                                   value="<?php echo $filters['end_date']; ?>">
                        </div>
                        
                        <div class="col-md-3 d-flex align-items-end gap-2">
                            <button type="submit" class="btn btn-primary flex-fill">
                                <i class="bi bi-filter"></i> Filter
                            </button>
                            <a href="<?php echo APP_URL; ?>/farm/transactions.php" class="btn btn-outline-secondary">
                                <i class="bi bi-x"></i>
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Transactions Table -->
    <div class="row">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom">
                    <h5 class="mb-0">
                        <i class="bi bi-list-ul"></i> Transaction History
                    </h5>
                </div>
                <div class="card-body">
                    <?php if (!empty($transactions)): ?>
                        <div class="table-responsive">
                            <table class="table table-hover align-middle">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Type</th>
                                        <th>Category</th>
                                        <th>Enterprise</th>
                                        <th>Description</th>
                                        <th class="text-end">Amount</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($transactions as $transaction): ?>
                                        <tr>
                                            <td>
                                                <small><?php echo formatDate($transaction['transaction_date']); ?></small>
                                            </td>
                                            <td>
                                                <?php if ($transaction['transaction_type'] === 'income'): ?>
                                                    <span class="badge bg-success">
                                                        <i class="bi bi-arrow-down-circle"></i> Income
                                                    </span>
                                                <?php else: ?>
                                                    <span class="badge bg-danger">
                                                        <i class="bi bi-arrow-up-circle"></i> Expense
                                                    </span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <small class="text-muted">
                                                    <?php echo htmlspecialchars($transaction['category'] ?: 'N/A'); ?>
                                                </small>
                                            </td>
                                            <td>
                                                <?php if ($transaction['enterprise_name']): ?>
                                                    <small class="badge bg-primary">
                                                        <?php echo htmlspecialchars($transaction['enterprise_name'] ?: ucfirst(str_replace('_', ' ', $transaction['enterprise_type']))); ?>
                                                    </small>
                                                <?php else: ?>
                                                    <small class="text-muted">General</small>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <small><?php echo htmlspecialchars($transaction['description']); ?></small>
                                            </td>
                                            <td class="text-end">
                                                <strong class="<?php echo $transaction['transaction_type'] === 'income' ? 'text-success' : 'text-danger'; ?>">
                                                    <?php echo $transaction['transaction_type'] === 'income' ? '+' : '-'; ?>
                                                    <?php echo formatCurrency($transaction['amount']); ?>
                                                </strong>
                                            </td>
                                            <td>
                                                <div class="btn-group btn-group-sm">
                                                    <button class="btn btn-outline-danger" 
                                                            onclick="deleteTransaction(<?php echo $transaction['id']; ?>)">
                                                        <i class="bi bi-trash"></i>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                                <tfoot class="table-light">
                                    <tr>
                                        <td colspan="5" class="text-end"><strong>Period Total:</strong></td>
                                        <td class="text-end">
                                            <strong class="<?php echo ($summary['net_profit'] ?? 0) >= 0 ? 'text-success' : 'text-danger'; ?>">
                                                <?php echo formatCurrency(abs($summary['net_profit'] ?? 0)); ?>
                                            </strong>
                                        </td>
                                        <td></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="text-center py-5">
                            <i class="bi bi-wallet2 text-muted" style="font-size: 4rem;"></i>
                            <h5 class="mt-3">No Transactions Found</h5>
                            <p class="text-muted">Start tracking your farm finances</p>
                            <a href="<?php echo APP_URL; ?>/farm/add-transaction.php" class="btn btn-success">
                                <i class="bi bi-plus-circle"></i> Add First Transaction
                            </a>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function deleteTransaction(transactionId) {
    confirmAction(
        'Delete Transaction',
        'Are you sure you want to delete this transaction?',
        function() {
            showLoading();
            $.post(APP_URL + '/ajax/delete-transaction.php', {
                transaction_id: transactionId
            }, function(response) {
                hideLoading();
                if (response.success) {
                    showToast(response.message, 'success');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showToast(response.message, 'error');
                }
            }).fail(function() {
                hideLoading();
                showToast('Connection error', 'error');
            });
        }
    );
}
</script>

<?php
include_once __DIR__ . '/../includes/footer.php';
include_once __DIR__ . '/../includes/bottom-nav.php';
?>
