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

$page_title = 'Dashboard';

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

$current_user = $auth->getCurrentUser();

// Get user statistics
$stats = [];

// Applications
$sql = "SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
        SUM(CASE WHEN status = 'approved' THEN 1 ELSE 0 END) as approved,
        SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected
        FROM rental_applications WHERE user_id = ?";
$stats['applications'] = $db->fetchOne($sql, [$current_user['id']]);

// Payments
$sql = "SELECT 
        COUNT(*) as total,
        SUM(amount) as total_paid,
        SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END) as completed_amount
        FROM payments WHERE user_id = ?";
$stats['payments'] = $db->fetchOne($sql, [$current_user['id']]);

// Recent applications
$sql = "SELECT * FROM rental_applications 
        WHERE user_id = ? 
        ORDER BY created_at DESC 
        LIMIT 3";
$recent_applications = $db->fetchAll($sql, [$current_user['id']]);

// 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']]);

// Recent activity
$sql = "SELECT * FROM activity_logs 
        WHERE user_id = ? 
        ORDER BY created_at DESC 
        LIMIT 5";
$recent_activity = $db->fetchAll($sql, [$current_user['id']]);

include 'includes/header.php';
?>

<!-- Welcome Banner -->
<div class="card mb-4" style="background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%); color: white;">
    <div class="card-body p-4">
        <div class="row align-items-center">
            <div class="col-md-8">
                <h2 class="mb-2">Welcome back, <?php echo htmlspecialchars($current_user['first_name']); ?>! 👋</h2>
                <p class="mb-0 opacity-75">Here's what's happening with your rental applications</p>
            </div>
            <div class="col-md-4 text-md-end">
                <a href="apply.php" class="btn btn-light btn-lg">
                    <i class="fas fa-plus"></i> New Application
                </a>
            </div>
        </div>
    </div>
</div>

<!-- Statistics Cards -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0">
                        <div style="width: 50px; height: 50px; background: rgba(0, 123, 255, 0.1); border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-file-alt fa-2x" style="color: #007bff;"></i>
                        </div>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h3 class="mb-0"><?php echo $stats['applications']['total']; ?></h3>
                        <p class="text-muted mb-0">Total Applications</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0">
                        <div style="width: 50px; height: 50px; background: rgba(255, 193, 7, 0.1); border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-clock fa-2x" style="color: #ffc107;"></i>
                        </div>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h3 class="mb-0"><?php echo $stats['applications']['pending']; ?></h3>
                        <p class="text-muted mb-0">Pending</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0">
                        <div style="width: 50px; height: 50px; background: rgba(40, 167, 69, 0.1); border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-check-circle fa-2x" style="color: #28a745;"></i>
                        </div>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h3 class="mb-0"><?php echo $stats['applications']['approved']; ?></h3>
                        <p class="text-muted mb-0">Approved</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0">
                        <div style="width: 50px; height: 50px; background: rgba(212, 160, 23, 0.1); border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-naira-sign fa-2x" style="color: var(--primary);"></i>
                        </div>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h3 class="mb-0">₦<?php echo number_format($stats['payments']['completed_amount'] ?? 0); ?></h3>
                        <p class="text-muted mb-0">Total Paid</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- Recent Applications -->
    <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-file-alt"></i> Recent Applications</h5>
                <a href="applications.php" class="btn btn-sm btn-outline-primary">View All</a>
            </div>
            <div class="card-body">
                <?php if (empty($recent_applications)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-file-alt fa-4x text-muted mb-3"></i>
                    <h5 class="text-muted">No applications yet</h5>
                    <p class="text-muted">Start your first rental application now!</p>
                    <a href="apply.php" class="btn btn-primary">
                        <i class="fas fa-plus"></i> New Application
                    </a>
                </div>
                <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Application #</th>
                                <th>Property</th>
                                <th>Amount</th>
                                <th>Status</th>
                                <th>Date</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($recent_applications as $app): ?>
                            <tr>
                                <td><strong><?php echo htmlspecialchars($app['application_number']); ?></strong></td>
                                <td><?php echo htmlspecialchars($app['property_address'] ?? 'Not specified'); ?></td>
                                <td><strong>₦<?php echo number_format($app['annual_rent']); ?></strong></td>
                                <td>
                                    <?php
                                    $badge_class = [
                                        'pending' => 'warning',
                                        'under_review' => 'info',
                                        'approved' => 'success',
                                        'rejected' => 'danger'
                                    ][$app['status']] ?? 'secondary';
                                    ?>
                                    <span class="badge bg-<?php echo $badge_class; ?>">
                                        <?php echo ucfirst(str_replace('_', ' ', $app['status'])); ?>
                                    </span>
                                </td>
                                <td><?php echo date('M d, Y', strtotime($app['created_at'])); ?></td>
                                <td>
                                    <a href="application-details.php?id=<?php echo $app['id']; ?>" class="btn btn-sm btn-outline-primary">
                                        <i class="fas fa-eye"></i> View
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- 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">
                <div class="list-group list-group-flush">
                    <?php foreach ($upcoming_payments as $payment): ?>
                    <div class="list-group-item d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="mb-1"><?php echo htmlspecialchars($payment['application_number']); ?></h6>
                            <small class="text-muted">
                                Due: <?php echo date('F d, Y', strtotime($payment['due_date'])); ?>
                            </small>
                        </div>
                        <div class="text-end">
                            <div class="h5 mb-1">₦<?php echo number_format($payment['amount_due']); ?></div>
                            <?php
                            $days_until = ceil((strtotime($payment['due_date']) - time()) / 86400);
                            if ($days_until <= 0):
                            ?>
                            <span class="badge bg-danger">Overdue</span>
                            <?php elseif ($days_until <= 7): ?>
                            <span class="badge bg-warning">Due in <?php echo $days_until; ?> days</span>
                            <?php else: ?>
                            <span class="badge bg-success">Due in <?php echo $days_until; ?> days</span>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
    
    <!-- Sidebar -->
    <div class="col-lg-4">
        <!-- Quick Actions -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-bolt"></i> Quick Actions</h5>
            </div>
            <div class="card-body">
                <div class="d-grid gap-2">
                    <a href="apply.php" class="btn btn-primary">
                        <i class="fas fa-plus-circle"></i> New Application
                    </a>
                    <a href="calculator.php" class="btn btn-outline-primary">
                        <i class="fas fa-calculator"></i> Rent Calculator
                    </a>
                    <a href="properties.php" class="btn btn-outline-primary">
                        <i class="fas fa-building"></i> Browse Properties
                    </a>
                    <a href="documents.php" class="btn btn-outline-primary">
                        <i class="fas fa-upload"></i> Upload Documents
                    </a>
                </div>
            </div>
        </div>
        
        <!-- Profile Completion -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-user-check"></i> Profile Status</h5>
            </div>
            <div class="card-body">
                <?php
                $completion = 0;
                if ($current_user['email_verified']) $completion += 20;
                if ($current_user['phone_verified']) $completion += 20;
                if ($current_user['bvn']) $completion += 20;
                if ($current_user['nin']) $completion += 20;
                if ($current_user['profile_photo']) $completion += 20;
                
                $color = $completion >= 80 ? 'success' : ($completion >= 50 ? 'warning' : 'danger');
                ?>
                
                <div class="mb-3">
                    <div class="d-flex justify-content-between mb-2">
                        <span>Profile Completion</span>
                        <strong><?php echo $completion; ?>%</strong>
                    </div>
                    <div class="progress" style="height: 10px;">
                        <div class="progress-bar bg-<?php echo $color; ?>" style="width: <?php echo $completion; ?>%"></div>
                    </div>
                </div>
                
                <div class="small">
                    <?php if (!$current_user['email_verified']): ?>
                    <div class="text-danger mb-1">
                        <i class="fas fa-times-circle"></i> Email not verified
                    </div>
                    <?php endif; ?>
                    
                    <?php if (!$current_user['phone_verified']): ?>
                    <div class="text-danger mb-1">
                        <i class="fas fa-times-circle"></i> Phone not verified
                    </div>
                    <?php endif; ?>
                    
                    <?php if (!$current_user['bvn']): ?>
                    <div class="text-warning mb-1">
                        <i class="fas fa-exclamation-circle"></i> BVN not provided
                    </div>
                    <?php endif; ?>
                </div>
                
                <?php if ($completion < 100): ?>
                <a href="profile.php" class="btn btn-sm btn-outline-primary w-100 mt-2">
                    <i class="fas fa-edit"></i> Complete Profile
                </a>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Recent Activity -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-history"></i> Recent Activity</h5>
            </div>
            <div class="card-body">
                <?php if (empty($recent_activity)): ?>
                <p class="text-muted text-center">No recent activity</p>
                <?php else: ?>
                <div class="activity-timeline">
                    <?php foreach ($recent_activity as $activity): ?>
                    <div class="activity-item mb-3 pb-3 border-bottom">
                        <div class="d-flex">
                            <div class="flex-shrink-0">
                                <i class="fas fa-circle text-primary" style="font-size: 0.5rem;"></i>
                            </div>
                            <div class="flex-grow-1 ms-3">
                                <p class="mb-1 small"><?php echo htmlspecialchars($activity['description']); ?></p>
                                <small class="text-muted">
                                    <?php
                                    $diff = time() - strtotime($activity['created_at']);
                                    if ($diff < 3600) {
                                        echo floor($diff / 60) . ' min ago';
                                    } elseif ($diff < 86400) {
                                        echo floor($diff / 3600) . ' hr ago';
                                    } else {
                                        echo date('M d, Y', strtotime($activity['created_at']));
                                    }
                                    ?>
                                </small>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

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