<?php
/**
 * VENDOR TRANSACTIONS PAGE - FIXED FOR NEW WALLET SYSTEM
 * File: vendor/transactions.php
 * View all wallet transactions with filters and export options
 */

require_once '../app/Core/init.php';
require_once '../app/Core/WalletStats.php';

// Require vendor authentication
Auth::requireVendor();

// Initialize models
$vendorModel = new Vendor();
$walletModel = new Wallet();
$walletTransactionModel = new WalletTransaction();

// Get current user ID
$user_id = Auth::id();

// Get vendor data
$vendor_data = $vendorModel->getByUserId($user_id);

if (!$vendor_data) {
    flash('error', 'Vendor profile not found.', 'danger');
    redirect('profile.php');
}

// Get or create wallet
$wallet_data = $walletModel->findByUserId($user_id);

if (!$wallet_data) {
    $walletModel->create($user_id);
    $wallet_data = $walletModel->findByUserId($user_id);
}

// Get wallet stats using WalletStats class
$walletStats = new WalletStats();
$wallet_stats = $walletStats->getVendorWalletCards($user_id);

// Format for display
$wallet_stats_display = [
    'balance' => WalletHelper::formatMoney($wallet_stats['available_balance']),
    'balance_raw' => $wallet_stats['available_balance'],
    'total_earned' => WalletHelper::formatMoney($wallet_stats['total_earned']),
    'total_earned_raw' => $wallet_stats['total_earned'],
    'total_withdrawn' => WalletHelper::formatMoney($wallet_stats['total_withdrawn']),
    'total_withdrawn_raw' => $wallet_stats['total_withdrawn'],
    'pending_earning' => WalletHelper::formatMoney($wallet_stats['pending_earning']),
    'pending_earning_raw' => $wallet_stats['pending_earning']
];

// Pagination for transactions
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 30;
$offset = ($page - 1) * $per_page;

// Get filters
$filter_type = $_GET['type'] ?? 'all';
$filter_category = $_GET['category'] ?? 'all';
$filter_status = $_GET['status'] ?? 'all';
$filter_date = $_GET['date'] ?? 'all';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';

$filters = ['user_id' => $user_id];

if ($filter_type !== 'all') {
    $filters['transaction_type'] = $filter_type;
}

if ($filter_category !== 'all') {
    $filters['category'] = $filter_category;
}

if ($filter_status !== 'all') {
    $filters['status'] = $filter_status;
}

// Date filters
if (!empty($date_from) && !empty($date_to)) {
    $filters['date_from'] = $date_from;
    $filters['date_to'] = $date_to;
} elseif ($filter_date !== 'all') {
    switch ($filter_date) {
        case 'today':
            $filters['date_from'] = date('Y-m-d');
            $filters['date_to'] = date('Y-m-d');
            break;
        case 'week':
            $filters['date_from'] = date('Y-m-d', strtotime('-7 days'));
            break;
        case 'month':
            $filters['date_from'] = date('Y-m-d', strtotime('-30 days'));
            break;
        case 'year':
            $filters['date_from'] = date('Y-m-d', strtotime('-365 days'));
            break;
    }
}

// Get transactions
$transactions = $walletTransactionModel->getAll($per_page, $offset, $filters);
$total_transactions = $walletTransactionModel->count($filters);
$total_pages = ceil($total_transactions / $per_page);

// Get transaction summary for current filter
$db = Database::getInstance();
$summary_sql = "SELECT 
                SUM(CASE WHEN category = 'credit' THEN amount ELSE 0 END) as total_credits,
                SUM(CASE WHEN category = 'debit' THEN amount ELSE 0 END) as total_debits,
                SUM(CASE WHEN transaction_type = 'vendor_earning' THEN amount ELSE 0 END) as total_earnings,
                SUM(CASE WHEN transaction_type = 'withdrawal' THEN amount ELSE 0 END) as total_withdrawals,
                SUM(CASE WHEN transaction_type = 'commission' THEN amount ELSE 0 END) as total_commission,
                COUNT(CASE WHEN category = 'credit' THEN 1 END) as credit_count,
                COUNT(CASE WHEN category = 'debit' THEN 1 END) as debit_count
                FROM wallet_transactions 
                WHERE user_id = ?";

$summary_params = [$user_id];

if (!empty($date_from) && !empty($date_to)) {
    $summary_sql .= " AND DATE(created_at) BETWEEN ? AND ?";
    $summary_params[] = $date_from;
    $summary_params[] = $date_to;
} elseif ($filter_date !== 'all') {
    switch ($filter_date) {
        case 'today':
            $summary_sql .= " AND DATE(created_at) = CURDATE()";
            break;
        case 'week':
            $summary_sql .= " AND DATE(created_at) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)";
            break;
        case 'month':
            $summary_sql .= " AND DATE(created_at) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)";
            break;
        case 'year':
            $summary_sql .= " AND DATE(created_at) >= DATE_SUB(CURDATE(), INTERVAL 365 DAY)";
            break;
    }
}

$summary = $db->fetch($summary_sql, $summary_params);

$page_title = "Transaction History";
include '../templates/layouts/vendor/header.php';
?>

<div class="container-fluid">
    <!-- Header -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <h1 class="h3 mb-0">Transaction History</h1>
                <div>
                    <a href="wallet.php" class="btn btn-outline-primary">
                        <i class="fas fa-wallet"></i> Back to Wallet
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="row mb-4">
        <div class="col-md-4">
            <div class="card bg-success text-white">
                <div class="card-body">
                    <h6 class="mb-2">Current Balance</h6>
                    <h3 class="mb-0"><?php echo $wallet_stats_display['balance']; ?></h3>
                    <small>Available for withdrawal</small>
                </div>
            </div>
        </div>

        <div class="col-md-4">
            <div class="card">
                <div class="card-body">
                    <h6 class="text-muted mb-2">Total Earnings</h6>
                    <h3 class="text-success mb-0"><?php echo WalletHelper::formatMoney($summary['total_earnings'] ?? 0); ?></h3>
                    <small class="text-muted">From completed orders</small>
                </div>
            </div>
        </div>

        <div class="col-md-4">
            <div class="card">
                <div class="card-body">
                    <h6 class="text-muted mb-2">Total Withdrawals</h6>
                    <h3 class="text-danger mb-0"><?php echo WalletHelper::formatMoney($summary['total_withdrawals'] ?? 0); ?></h3>
                    <small class="text-muted"><?php echo number_format($summary['debit_count'] ?? 0); ?> transactions</small>
                </div>
            </div>
        </div>

    </div>

    <!-- Filters & Transactions -->
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">All Transactions</h5>
            <span class="badge badge-primary"><?php echo number_format($total_transactions); ?> Total</span>
        </div>
        <div class="card-body">
            <!-- Filters -->
            <form method="GET" class="mb-4">
                <div class="row">
                    <div class="col-md-3">
                        <label class="small">Transaction Type</label>
                        <select name="type" class="form-control form-control-sm">
                            <option value="all">All Types</option>
                            <option value="vendor_earning" <?php echo $filter_type === 'vendor_earning' ? 'selected' : ''; ?>>Vendor Earnings</option>
                            <option value="withdrawal" <?php echo $filter_type === 'withdrawal' ? 'selected' : ''; ?>>Withdrawals</option>
                            <option value="commission" <?php echo $filter_type === 'commission' ? 'selected' : ''; ?>>Platform Commission</option>
                            <option value="dispute_deduction" <?php echo $filter_type === 'dispute_deduction' ? 'selected' : ''; ?>>Dispute Deductions</option>
                            <option value="admin_fee" <?php echo $filter_type === 'admin_fee' ? 'selected' : ''; ?>>Admin Fees</option>
                        </select>
                    </div>

                    <div class="col-md-2">
                        <label class="small">Category</label>
                        <select name="category" class="form-control form-control-sm">
                            <option value="all">All</option>
                            <option value="credit" <?php echo $filter_category === 'credit' ? 'selected' : ''; ?>>Credits</option>
                            <option value="debit" <?php echo $filter_category === 'debit' ? 'selected' : ''; ?>>Debits</option>
                        </select>
                    </div>

                    <div class="col-md-2">
                        <label class="small">Status</label>
                        <select name="status" class="form-control form-control-sm">
                            <option value="all">All</option>
                            <option value="completed" <?php echo $filter_status === 'completed' ? 'selected' : ''; ?>>Completed</option>
                            <option value="pending" <?php echo $filter_status === 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="failed" <?php echo $filter_status === 'failed' ? 'selected' : ''; ?>>Failed</option>
                        </select>
                    </div>

                    <div class="col-md-2">
                        <label class="small">Period</label>
                        <select name="date" class="form-control form-control-sm" id="periodSelect">
                            <option value="all">All Time</option>
                            <option value="today" <?php echo $filter_date === 'today' ? 'selected' : ''; ?>>Today</option>
                            <option value="week" <?php echo $filter_date === 'week' ? 'selected' : ''; ?>>Last 7 Days</option>
                            <option value="month" <?php echo $filter_date === 'month' ? 'selected' : ''; ?>>Last 30 Days</option>
                            <option value="year" <?php echo $filter_date === 'year' ? 'selected' : ''; ?>>Last Year</option>
                            <option value="custom" <?php echo (!empty($date_from) && !empty($date_to)) ? 'selected' : ''; ?>>Custom Range</option>
                        </select>
                    </div>

                    <div class="col-md-3">
                        <label class="small">&nbsp;</label>
                        <button type="submit" class="btn btn-primary btn-sm btn-block">
                            <i class="fas fa-filter"></i> Apply Filters
                        </button>
                    </div>
                </div>

                <!-- Custom Date Range -->
                <div class="row mt-3" id="customDateRange" style="display: <?php echo (!empty($date_from) && !empty($date_to)) ? 'block' : 'none'; ?>;">
                    <div class="col-md-3">
                        <label class="small">From Date</label>
                        <input type="date" name="date_from" class="form-control form-control-sm" 
                               value="<?php echo htmlspecialchars($date_from); ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="small">To Date</label>
                        <input type="date" name="date_to" class="form-control form-control-sm" 
                               value="<?php echo htmlspecialchars($date_to); ?>">
                    </div>
                </div>

                <?php if ($filter_type !== 'all' || $filter_category !== 'all' || $filter_status !== 'all' || $filter_date !== 'all'): ?>
                    <div class="row mt-3">
                        <div class="col-12">
                            <a href="transactions.php" class="btn btn-sm btn-outline-secondary">
                                <i class="fas fa-times"></i> Clear All Filters
                            </a>
                        </div>
                    </div>
                <?php endif; ?>
            </form>

            <!-- Transactions Table -->
            <?php if (empty($transactions)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-receipt fa-3x text-muted mb-3"></i>
                    <p class="text-muted">No transactions found</p>
                    <small class="text-muted">Transactions will appear here once orders are completed</small>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Date & Time</th>
                                <th>Type</th>
                                <th>Description</th>
                                <th>Reference</th>
                                <th>Amount</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($transactions as $txn): ?>
                                <tr>
                                    <td>
                                        <strong><?php echo date('M d, Y', strtotime($txn['created_at'])); ?></strong>
                                        <br>
                                        <small class="text-muted"><?php echo date('h:i A', strtotime($txn['created_at'])); ?></small>
                                    </td>
                                    <td>
                                        <span class="badge bg-<?php echo ($txn['category'] ?? 'credit') === 'credit' ? 'success' : 'warning'; ?>">
                                            <?php echo WalletHelper::getTransactionTypeLabel($txn['transaction_type'] ?? ''); ?>
                                        </span>
                                        <br>
                                        <small class="text-muted"><?php echo ucfirst($txn['category'] ?? 'credit'); ?></small>
                                    </td>
                                    <td>
                                        <?php echo htmlspecialchars($txn['description'] ?? ''); ?>
                                        <?php if (!empty($txn['order_number'])): ?>
                                            <br>
                                            <small class="text-muted">
                                                Order: <a href="orders/view.php?order_number=<?php echo htmlspecialchars($txn['order_number']); ?>">
                                                    <?php echo htmlspecialchars($txn['order_number']); ?>
                                                </a>
                                            </small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <small class="font-monospace"><?php echo htmlspecialchars($txn['reference'] ?? 'N/A'); ?></small>
                                    </td>
                                    <td>
                                        <strong class="<?php echo ($txn['category'] ?? 'credit') === 'credit' ? 'text-success' : 'text-danger'; ?>">
                                            <?php echo ($txn['category'] ?? 'credit') === 'credit' ? '+' : '-'; ?>
                                            <?php echo WalletHelper::formatMoney($txn['amount'] ?? 0); ?>
                                        </strong>
                                    </td>
                                    <td>
                                        <?php
                                            $badge_class = 'secondary';
                                            switch($txn['status']) {
                                                case 'pending': $badge_class = 'warning'; break;
                                                case 'confirmed': $badge_class = 'info'; break;
                                                case 'ongoing': $badge_class = 'primary'; break;
                                                case 'completed': $badge_class = 'success'; break;
                                                case 'cancelled': $badge_class = 'danger'; break;
                                            }
                                        ?>
                                        <span class="text-<?php echo $badge_class; ?>">
                                            <b><?php echo ucfirst($txn['status'] ?? 'completed'); ?></b>
                                        </span>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <tr class="table-active">
                                <td colspan="4" class="text-right"><strong>Page Total:</strong></td>
                                <td>
                                    <strong class="text-success">
                                        +<?php 
                                        $page_credits = array_sum(array_map(function($t) { 
                                            return ($t['category'] ?? 'credit') === 'credit' ? ($t['amount'] ?? 0) : 0; 
                                        }, $transactions));
                                        echo WalletHelper::formatMoney($page_credits); 
                                        ?>
                                    </strong>
                                    <br>
                                    <strong class="text-danger">
                                        -<?php 
                                        $page_debits = array_sum(array_map(function($t) { 
                                            return ($t['category'] ?? 'credit') === 'debit' ? ($t['amount'] ?? 0) : 0; 
                                        }, $transactions));
                                        echo WalletHelper::formatMoney($page_debits); 
                                        ?>
                                    </strong>
                                </td>
                                <td colspan="2"></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>

                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                    <nav>
                        <ul class="pagination justify-content-center">
                            <?php if ($page > 1): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page - 1; ?>&type=<?php echo $filter_type; ?>&category=<?php echo $filter_category; ?>&status=<?php echo $filter_status; ?>&date=<?php echo $filter_date; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>">
                                        <i class="fas fa-chevron-left"></i> Previous
                                    </a>
                                </li>
                            <?php endif; ?>

                            <?php 
                            $start_page = max(1, $page - 2);
                            $end_page = min($total_pages, $page + 2);
                            
                            for ($i = $start_page; $i <= $end_page; $i++): 
                            ?>
                                <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>&type=<?php echo $filter_type; ?>&category=<?php echo $filter_category; ?>&status=<?php echo $filter_status; ?>&date=<?php echo $filter_date; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>">
                                        <?php echo $i; ?>
                                    </a>
                                </li>
                            <?php endfor; ?>

                            <?php if ($page < $total_pages): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page + 1; ?>&type=<?php echo $filter_type; ?>&category=<?php echo $filter_category; ?>&status=<?php echo $filter_status; ?>&date=<?php echo $filter_date; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>">
                                        Next <i class="fas fa-chevron-right"></i>
                                    </a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </nav>

                    <p class="text-center text-muted small">
                        Showing <?php echo (($page - 1) * $per_page) + 1; ?> to <?php echo min($page * $per_page, $total_transactions); ?> of <?php echo number_format($total_transactions); ?> transactions
                    </p>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
// Show/hide custom date range
document.getElementById('periodSelect').addEventListener('change', function() {
    const customRange = document.getElementById('customDateRange');
    if (this.value === 'custom') {
        customRange.style.display = 'block';
    } else {
        customRange.style.display = 'none';
    }
});
</script>

<?php include '../templates/layouts/vendor/footer.php'; ?>