<?php
define('ROVO_APP', true);
require_once '../config.php';
require_once '../Auth.php';

$page_title = 'Payment History';

if (!$auth->isLoggedIn() || $auth->isAdmin()) {
    header('Location: ../login.php');
    exit;
}

$current_user = $auth->getCurrentUser();

// Get application filter if specified
$application_filter = isset($_GET['application']) ? (int)$_GET['application'] : 0;

// Get all payments
$sql = "SELECT p.*, ra.application_number, ra.property_address 
        FROM payments p
        LEFT JOIN rental_applications ra ON p.related_id = ra.id AND p.related_type = 'rental_application'
        WHERE p.user_id = ?";
$params = [$current_user['id']];

if ($application_filter) {
    $sql .= " AND p.related_id = ?";
    $params[] = $application_filter;
}

$sql .= " ORDER BY p.created_at DESC";

$payments = $db->fetchAll($sql, $params);

// Get payment statistics
$stats_sql = "SELECT 
              COUNT(*) as total_count,
              SUM(amount) as total_amount,
              SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END) as paid_amount,
              SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END) as pending_amount
              FROM payments 
              WHERE user_id = ?";
$stats = $db->fetchOne($stats_sql, [$current_user['id']]);

// Get upcoming rent payments
$sql = "SELECT rp.*, ra.application_number 
        FROM rent_payments rp
        JOIN rental_applications ra ON rp.rental_application_id = ra.id
        WHERE ra.user_id = ? AND rp.status IN ('pending', 'partial')
        ORDER BY rp.due_date ASC
        LIMIT 5";
$upcoming_payments = $db->fetchAll($sql, [$current_user['id']]);

include 'includes/header.php';
?>

<style>
    .payment-card {
        transition: all 0.3s;
    }
    
    .payment-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }
    
    .stat-card {
        padding: 20px;
        border-radius: 10px;
        text-align: center;
    }
    
    .stat-value {
        font-size: 1.8rem;
        font-weight: bold;
        margin: 10px 0;
    }
    
    .payment-timeline {
        position: relative;
        padding-left: 30px;
    }
    
    .payment-timeline::before {
        content: '';
        position: absolute;
        left: 8px;
        top: 0;
        bottom: 0;
        width: 2px;
        background: #e0e0e0;
    }
    
    .timeline-item {
        position: relative;
        margin-bottom: 25px;
    }
    
    .timeline-item::before {
        content: '';
        position: absolute;
        left: -26px;
        top: 4px;
        width: 16px;
        height: 16px;
        border-radius: 50%;
        background: white;
        border: 3px solid #e0e0e0;
    }
    
    .timeline-item.completed::before {
        background: #28a745;
        border-color: #28a745;
    }
    
    .timeline-item.pending::before {
        background: #ffc107;
        border-color: #ffc107;
    }
    
    .timeline-item.failed::before {
        background: #dc3545;
        border-color: #dc3545;
    }
</style>

<div class="page-header">
    <h1>Payment History</h1>
    <p class="text-muted mb-0">Track all your payments and transactions</p>
</div>

<!-- Statistics Cards -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card stat-card" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
            <i class="fas fa-receipt fa-2x text-white mb-2"></i>
            <div class="stat-value text-white"><?php echo $stats['total_count'] ?? 0; ?></div>
            <div class="text-white opacity-75">Total Transactions</div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card stat-card" style="background: linear-gradient(135deg, #28a745 0%, #20c997 100%);">
            <i class="fas fa-check-circle fa-2x text-white mb-2"></i>
            <div class="stat-value text-white">₦<?php echo number_format($stats['paid_amount'] ?? 0); ?></div>
            <div class="text-white opacity-75">Total Paid</div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card stat-card" style="background: linear-gradient(135deg, #ffc107 0%, #ff9800 100%);">
            <i class="fas fa-clock fa-2x text-white mb-2"></i>
            <div class="stat-value text-white">₦<?php echo number_format($stats['pending_amount'] ?? 0); ?></div>
            <div class="text-white opacity-75">Pending</div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card stat-card" style="background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);">
            <i class="fas fa-calendar-check fa-2x text-white mb-2"></i>
            <div class="stat-value text-white"><?php echo count($upcoming_payments); ?></div>
            <div class="text-white opacity-75">Upcoming Payments</div>
        </div>
    </div>
</div>

<div class="row">
    <!-- Payment History -->
    <div class="col-lg-8">
        <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="fas fa-history"></i> Transaction History</h5>
                <button class="btn btn-sm btn-outline-primary" onclick="window.print()">
                    <i class="fas fa-print"></i> Print
                </button>
            </div>
            <div class="card-body">
                <?php if (empty($payments)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-receipt fa-5x text-muted mb-3"></i>
                    <h5 class="text-muted">No Payments Yet</h5>
                    <p class="text-muted">Your payment history will appear here</p>
                </div>
                <?php else: ?>
                <div class="payment-timeline">
                    <?php foreach ($payments as $payment): ?>
                    <div class="timeline-item <?php echo $payment['status']; ?>">
                        <div class="card payment-card mb-3">
                            <div class="card-body">
                                <div class="row align-items-center">
                                    <div class="col-md-8">
                                        <div class="d-flex align-items-center mb-2">
                                            <div class="me-3">
                                                <?php
                                                $icon_class = [
                                                    'completed' => 'fa-check-circle text-success',
                                                    'pending' => 'fa-clock text-warning',
                                                    'failed' => 'fa-times-circle text-danger',
                                                    'processing' => 'fa-spinner fa-spin text-info'
                                                ][$payment['status']] ?? 'fa-circle text-secondary';
                                                ?>
                                                <i class="fas <?php echo $icon_class; ?> fa-2x"></i>
                                            </div>
                                            <div>
                                                <h6 class="mb-1">
                                                    <?php echo ucfirst(str_replace('_', ' ', $payment['payment_type'])); ?> Payment
                                                </h6>
                                                <?php if (!empty($payment['application_number'])): ?>
                                                <small class="text-muted">
                                                    Application: <?php echo htmlspecialchars($payment['application_number']); ?>
                                                </small>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        
                                        <small class="text-muted">
                                            <i class="far fa-calendar"></i>
                                            <?php echo date('F d, Y \a\t H:i', strtotime($payment['created_at'])); ?>
                                        </small>
                                        
                                        <?php if (!empty($payment['description'])): ?>
                                        <p class="mb-0 mt-2 small"><?php echo htmlspecialchars($payment['description']); ?></p>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <div class="col-md-4 text-md-end">
                                        <h4 class="mb-2" style="color: var(--primary);">
                                            ₦<?php echo number_format($payment['amount']); ?>
                                        </h4>
                                        
                                        <?php
                                        $status_badge = [
                                            'completed' => 'success',
                                            'pending' => 'warning',
                                            'failed' => 'danger',
                                            'processing' => 'info',
                                            'cancelled' => 'secondary'
                                        ][$payment['status']] ?? 'secondary';
                                        ?>
                                        <span class="badge bg-<?php echo $status_badge; ?>">
                                            <?php echo ucfirst($payment['status']); ?>
                                        </span>
                                        
                                        <?php if (!empty($payment['transaction_reference'])): ?>
                                        <div class="mt-2">
                                            <small class="text-muted">
                                                Ref: <?php echo htmlspecialchars($payment['transaction_reference']); ?>
                                            </small>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($payment['status'] === 'pending'): ?>
                                        <button class="btn btn-sm btn-success mt-2 complete-payment"
                                                data-id="<?php echo $payment['id']; ?>"
                                                data-amount="<?php echo $payment['amount']; ?>">
                                            <i class="fas fa-credit-card"></i> Pay Now
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <!-- Sidebar -->
    <div class="col-lg-4">
        <!-- Upcoming Payments -->
        <?php if (!empty($upcoming_payments)): ?>
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-calendar-alt"></i> Upcoming Payments</h5>
            </div>
            <div class="card-body">
                <?php foreach ($upcoming_payments as $upcoming): ?>
                <div class="mb-3 pb-3 border-bottom">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <h6 class="mb-1"><?php echo htmlspecialchars($upcoming['application_number']); ?></h6>
                            <small class="text-muted">
                                Due: <?php echo date('M d, Y', strtotime($upcoming['due_date'])); ?>
                            </small>
                        </div>
                        <div class="text-end">
                            <strong class="text-primary">₦<?php echo number_format($upcoming['amount_due']); ?></strong>
                            <?php
                            $days_until = ceil((strtotime($upcoming['due_date']) - time()) / 86400);
                            if ($days_until <= 0):
                            ?>
                            <br><span class="badge bg-danger">Overdue</span>
                            <?php elseif ($days_until <= 7): ?>
                            <br><span class="badge bg-warning">Due Soon</span>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Payment Methods -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-credit-card"></i> Payment Methods</h5>
            </div>
            <div class="card-body">
                <div class="d-grid gap-2">
                    <div class="p-3 border rounded d-flex align-items-center">
                        <i class="fab fa-cc-visa fa-2x text-primary me-3"></i>
                        <div>
                            <strong>Card Payment</strong>
                            <br>
                            <small class="text-muted">Visa, Mastercard</small>
                        </div>
                    </div>
                    
                    <div class="p-3 border rounded d-flex align-items-center">
                        <i class="fas fa-university fa-2x text-success me-3"></i>
                        <div>
                            <strong>Bank Transfer</strong>
                            <br>
                            <small class="text-muted">Direct transfer</small>
                        </div>
                    </div>
                    
                    <div class="p-3 border rounded d-flex align-items-center">
                        <i class="fas fa-mobile-alt fa-2x text-info me-3"></i>
                        <div>
                            <strong>USSD</strong>
                            <br>
                            <small class="text-muted">Pay with *code#</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Help -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-question-circle"></i> Need Help?</h5>
            </div>
            <div class="card-body">
                <p class="small text-muted mb-3">
                    Having issues with payments? Our support team is here to help.
                </p>
                <div class="d-grid gap-2">
                    <a href="messages.php?new=1&topic=payment" class="btn btn-outline-primary">
                        <i class="fas fa-envelope"></i> Contact Support
                    </a>
                    <a href="https://wa.me/2349065136669" target="_blank" class="btn btn-outline-success">
                        <i class="fab fa-whatsapp"></i> WhatsApp
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Payment Modal -->
<div class="modal fade" id="paymentModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Complete Payment</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="text-center mb-4">
                    <h3 id="paymentAmount" style="color: var(--primary);">₦0</h3>
                    <p class="text-muted">Amount to Pay</p>
                </div>
                
                <div class="d-grid gap-2">
                    <button class="btn btn-primary btn-lg" id="paystackBtn">
                        <i class="fas fa-credit-card"></i> Pay with Card
                    </button>
                    <button class="btn btn-outline-primary" id="bankTransferBtn">
                        <i class="fas fa-university"></i> Bank Transfer
                    </button>
                    <button class="btn btn-outline-info" id="ussdBtn">
                        <i class="fas fa-mobile-alt"></i> Pay with USSD
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    let currentPaymentId = null;
    let currentAmount = 0;
    
    // Open payment modal
    $('.complete-payment').click(function() {
        currentPaymentId = $(this).data('id');
        currentAmount = $(this).data('amount');
        
        $('#paymentAmount').text('₦' + currentAmount.toLocaleString());
        $('#paymentModal').modal('show');
    });
    
    // Paystack payment
    $('#paystackBtn').click(function() {
        Swal.fire({
            icon: 'info',
            title: 'Payment Gateway',
            text: 'Paystack integration will be implemented here',
            confirmButtonText: 'OK'
        });
    });
    
    // Bank transfer
    $('#bankTransferBtn').click(function() {
        Swal.fire({
            icon: 'info',
            title: 'Bank Transfer Details',
            html: `
                <p>Make a transfer to:</p>
                <div class="text-start">
                    <strong>Bank:</strong> GTBank<br>
                    <strong>Account Name:</strong> RoVo Nigeria<br>
                    <strong>Account Number:</strong> 0123456789<br>
                    <strong>Amount:</strong> ₦${currentAmount.toLocaleString()}
                </div>
                <p class="mt-3 small text-muted">
                    After making the transfer, please send proof of payment to our WhatsApp.
                </p>
            `,
            confirmButtonText: 'OK'
        });
    });
    
    // USSD
    $('#ussdBtn').click(function() {
        Swal.fire({
            icon: 'info',
            title: 'USSD Payment',
            html: `
                <p>Dial the USSD code on your phone:</p>
                <h3 class="text-primary">*737*000*${currentAmount}#</h3>
                <p class="small text-muted mt-3">
                    Follow the prompts to complete payment
                </p>
            `,
            confirmButtonText: 'OK'
        });
    });
});
</script>

<?php include 'includes/footer.php'; ?>