<?php
/**
 * CUSTOMER TRANSACTIONS PAGE
 * File: customer/transactions.php
 * View all wallet transactions with filters
 */

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

// Require customer authentication
Auth::requireCustomer();

// Initialize models
$customerModel = new Customer();
$walletModel = new Wallet();
$walletTransactionModel = new WalletTransaction();

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

// Get customer data
$customer_data = $customerModel->findByUserId($user_id);

if (!$customer_data) {
    flash('error', 'Please complete your profile first.', '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
$wallet_stats = WalletHelper::getDashboardStats($user_id);

// 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,
                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 = "Transactions";
$active_menu = "transactions";

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

<body class="fixed sidebar-mini">
    <div class="wrapper">
        <!-- Sidebar -->
        <nav class="sidebar">
            <div class="sidebar-header">
                <?php include '../templates/layouts/customer/navbar.php'; ?>
            </div>
        </nav>

        

        <!-- Page Content -->
        <div class="content-wrapper">

            <div class="main-content">
                <?php include '../templates/layouts/customer/header.php'; ?>
                
                <!-- Page Header -->
                <div class="page-header">
                    <div class="page-title">
                        <h1>Dashboard</h1>
                        <ul class="breadcrumb">
                            <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                            <li class="breadcrumb-item active">Dashboard</li>
                        </ul>
                    </div>
                </div>

<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>
                <a href="wallet.php" class="btn btn-outline-primary">
                    <i class="fas fa-wallet"></i> Back to Wallet
                </a>
            </div>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="row mb-4">
        <div class="col-md-3">
            <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['balance']; ?></h3>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <h6 class="text-muted mb-2">Total Credits</h6>
                    <h3 class="text-success mb-0"><?php echo WalletHelper::formatMoney($summary['total_credits'] ?? 0); ?></h3>
                    <small class="text-muted"><?php echo number_format($summary['credit_count'] ?? 0); ?> transactions</small>
                </div>
            </div>
        </div>

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

        <div class="col-md-3">
            <div class="card">
                <div class="card-body">
                    <h6 class="text-muted mb-2">Total Transactions</h6>
                    <h3 class="mb-0"><?php echo number_format($total_transactions); ?></h3>
                    <small class="text-muted">In selected period</small>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters & Transactions -->
    <div class="card">
        <div class="card-header">
            <h5 class="mb-0">All Transactions</h5>
        </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="security_refund" <?php echo $filter_type === 'security_refund' ? 'selected' : ''; ?>>Security Refunds</option>
                            <option value="cancellation_refund" <?php echo $filter_type === 'cancellation_refund' ? 'selected' : ''; ?>>Cancellation Refunds</option>
                            <option value="rental_payment" <?php echo $filter_type === 'rental_payment' ? 'selected' : ''; ?>>Rental Payments</option>
                            <option value="top_up" <?php echo $filter_type === 'top_up' ? 'selected' : ''; ?>>Wallet Top-ups</option>
                            <option value="dispute_deduction" <?php echo $filter_type === 'dispute_deduction' ? 'selected' : ''; ?>>Dispute Deductions</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>
                </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>
                            </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>
                                        <?php
                                            $badge_class = 'secondary';
                                            switch($txn['category']) {
                                                case 'credit': $badge_class = 'success'; break;
                                                case 'debit': $badge_class = 'danger'; break;
                                            }
                                        ?>
                                        <?php /* <span class="badge bg-<?php echo ($txn['category'] ?? 'credit') === 'credit' ? 'success' : 'warning'; ?>"> */ ?>
                                            <span class="badge bg-<?php echo $badge_class; ?>">
                                            <?php echo WalletHelper::getTransactionTypeLabel($txn['transaction_type'] ?? ''); ?>
                                        </span>
                                        <br>                                        
                                        <?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; ?>">
                                            <?php echo ucfirst($txn['status'] ?? 'completed'); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php echo htmlspecialchars($txn['description'] ?? ''); ?>
                                        <?php if (!empty($txn['order_number'])): ?>
                                            <br>
                                            <small class="text-muted">
                                                Order: <a href="order-details.php?id=<?php echo htmlspecialchars($txn['order_id']); ?>">
                                                    <?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 WalletHelper::formatMoney($txn['amount'] ?? 0); ?>
                                        </strong>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </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/customer/footer.php'; ?>