<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

$page_title = 'Dashboard';

// Get statistics
$stats = [];

// Total Properties
$sql = "SELECT COUNT(*) as total, 
        SUM(CASE WHEN status = 'available' THEN 1 ELSE 0 END) as available,
        SUM(CASE WHEN status = 'sold' THEN 1 ELSE 0 END) as sold,
        SUM(CASE WHEN status = 'rented' THEN 1 ELSE 0 END) as rented
        FROM properties";
$stats['properties'] = $db->fetchOne($sql);

// Total Lands
$sql = "SELECT COUNT(*) as total,
        SUM(CASE WHEN status = 'available' THEN 1 ELSE 0 END) as available,
        SUM(CASE WHEN status = 'sold' THEN 1 ELSE 0 END) as sold
        FROM lands";
$stats['lands'] = $db->fetchOne($sql);

// Total Users
$sql = "SELECT COUNT(*) as total,
        SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active,
        SUM(CASE WHEN role != 'user' THEN 1 ELSE 0 END) as admins
        FROM users";
$stats['users'] = $db->fetchOne($sql);

// Rental 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";
$stats['applications'] = $db->fetchOne($sql);

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

// Recent activities
$sql = "SELECT al.*, u.first_name, u.last_name 
        FROM activity_logs al
        LEFT JOIN users u ON al.user_id = u.id
        ORDER BY al.created_at DESC
        LIMIT 10";
$recent_activities = $db->fetchAll($sql);

// Recent applications
$sql = "SELECT ra.*, u.email, u.phone
        FROM rental_applications ra
        JOIN users u ON ra.user_id = u.id
        ORDER BY ra.created_at DESC
        LIMIT 5";
$recent_applications = $db->fetchAll($sql);

// Monthly revenue data for chart
$sql = "SELECT DATE_FORMAT(created_at, '%Y-%m') as month, 
        SUM(amount) as revenue
        FROM payments
        WHERE status = 'completed' AND created_at >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
        GROUP BY month
        ORDER BY month";
$monthly_revenue = $db->fetchAll($sql);

// Application status distribution
$sql = "SELECT status, COUNT(*) as count
        FROM rental_applications
        GROUP BY status";
$application_stats = $db->fetchAll($sql);

include 'includes/header.php';
?>

<div class="page-header">
    <h1>Dashboard Overview</h1>
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item active">Dashboard</li>
        </ol>
    </nav>
</div>

<!-- Statistics Cards -->
<div class="row">
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stat-card">
            <div>
                <div class="stat-icon" style="background: rgba(0, 123, 255, 0.1); color: #007bff;">
                    <i class="fas fa-building"></i>
                </div>
            </div>
            <div class="stat-info text-end">
                <h3><?php echo number_format($stats['properties']['total']); ?></h3>
                <p>Total Properties</p>
                <div class="stat-trend up">
                    <i class="fas fa-arrow-up"></i> <?php echo $stats['properties']['available']; ?> Available
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stat-card">
            <div>
                <div class="stat-icon" style="background: rgba(40, 167, 69, 0.1); color: #28a745;">
                    <i class="fas fa-users"></i>
                </div>
            </div>
            <div class="stat-info text-end">
                <h3><?php echo number_format($stats['users']['total']); ?></h3>
                <p>Total Users</p>
                <div class="stat-trend up">
                    <i class="fas fa-arrow-up"></i> <?php echo $stats['users']['active']; ?> Active
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stat-card">
            <div>
                <div class="stat-icon" style="background: rgba(255, 193, 7, 0.1); color: #ffc107;">
                    <i class="fas fa-file-alt"></i>
                </div>
            </div>
            <div class="stat-info text-end">
                <h3><?php echo number_format($stats['applications']['total']); ?></h3>
                <p>Applications</p>
                <div class="stat-trend" style="color: #ffc107;">
                    <i class="fas fa-clock"></i> <?php echo $stats['applications']['pending']; ?> Pending
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stat-card">
            <div>
                <div class="stat-icon" style="background: rgba(220, 53, 69, 0.1); color: #dc3545;">
                    <i class="fas fa-naira-sign"></i>
                </div>
            </div>
            <div class="stat-info text-end">
                <h3>₦<?php echo number_format($stats['payments']['completed_amount'] ?? 0); ?></h3>
                <p>Total Revenue</p>
                <div class="stat-trend up">
                    <i class="fas fa-arrow-up"></i> <?php echo $stats['payments']['total']; ?> Transactions
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- Revenue Chart -->
    <div class="col-lg-8 mb-4">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Revenue Overview</h5>
                <div class="btn-group btn-group-sm" role="group">
                    <button type="button" class="btn btn-outline-secondary active">6 Months</button>
                    <button type="button" class="btn btn-outline-secondary">1 Year</button>
                </div>
            </div>
            <div class="card-body">
                <canvas id="revenueChart" height="300"></canvas>
            </div>
        </div>
    </div>
    
    <!-- Application Status Distribution -->
    <div class="col-lg-4 mb-4">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">Application Status</h5>
            </div>
            <div class="card-body">
                <canvas id="applicationChart" height="300"></canvas>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- Recent Applications -->
    <div class="col-lg-8 mb-4">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Recent Applications</h5>
                <a href="rental-applications.php" class="btn btn-sm btn-primary">View All</a>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead>
                            <tr>
                                <th>Application #</th>
                                <th>Name</th>
                                <th>Email</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['full_name']); ?></td>
                                <td><?php echo htmlspecialchars($app['email']); ?></td>
                                <td>₦<?php echo number_format($app['annual_rent']); ?></td>
                                <td>
                                    <?php
                                    $badge_class = [
                                        'pending' => 'warning',
                                        'approved' => 'success',
                                        'rejected' => 'danger',
                                        'under_review' => 'info'
                                    ][$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="rental-applications.php?view=<?php echo $app['id']; ?>" 
                                       class="btn btn-sm btn-outline-primary">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Recent Activities -->
    <div class="col-lg-4 mb-4">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">Recent Activities</h5>
            </div>
            <div class="card-body" style="max-height: 400px; overflow-y: auto;">
                <?php foreach ($recent_activities as $activity): ?>
                <div class="d-flex align-items-start mb-3 pb-3 border-bottom">
                    <div class="flex-shrink-0">
                        <div class="rounded-circle d-flex align-items-center justify-content-center"
                             style="width: 40px; height: 40px; background: rgba(212, 160, 23, 0.1);">
                            <i class="fas fa-<?php 
                                echo match($activity['action']) {
                                    'login' => 'sign-in-alt',
                                    'register' => 'user-plus',
                                    'create' => 'plus',
                                    'update' => 'edit',
                                    'delete' => 'trash',
                                    default => 'circle'
                                };
                            ?>" style="color: var(--primary);"></i>
                        </div>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <p class="mb-1">
                            <strong><?php echo htmlspecialchars($activity['first_name'] . ' ' . $activity['last_name']); ?></strong>
                            <?php echo htmlspecialchars($activity['description']); ?>
                        </p>
                        <small class="text-muted">
                            <i class="far fa-clock"></i>
                            <?php 
                            $time = strtotime($activity['created_at']);
                            echo date('M d, Y H:i', $time);
                            ?>
                        </small>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>

<!-- Quick Actions -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">Quick Actions</h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <?php if ($auth->hasPermission('can_create') || $auth->hasRole('super_admin')): ?>
                    <div class="col-md-3">
                        <a href="properties.php?action=add" class="btn btn-outline-primary w-100 py-3">
                            <i class="fas fa-plus-circle fa-2x d-block mb-2"></i>
                            Add New Property
                        </a>
                    </div>
                    <div class="col-md-3">
                        <a href="lands.php?action=add" class="btn btn-outline-success w-100 py-3">
                            <i class="fas fa-map-marked-alt fa-2x d-block mb-2"></i>
                            Add New Land
                        </a>
                    </div>
                    <?php endif; ?>
                    
                    <div class="col-md-3">
                        <a href="rental-applications.php?status=pending" class="btn btn-outline-warning w-100 py-3">
                            <i class="fas fa-file-alt fa-2x d-block mb-2"></i>
                            Review Applications
                        </a>
                    </div>
                    
                    <?php if ($auth->hasPermission('can_manage_users') || $auth->hasRole('super_admin')): ?>
                    <div class="col-md-3">
                        <a href="users.php" class="btn btn-outline-info w-100 py-3">
                            <i class="fas fa-users fa-2x d-block mb-2"></i>
                            Manage Users
                        </a>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // Revenue Chart
    const revenueCtx = document.getElementById('revenueChart').getContext('2d');
    const revenueChart = new Chart(revenueCtx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode(array_column($monthly_revenue, 'month')); ?>,
            datasets: [{
                label: 'Revenue (₦)',
                data: <?php echo json_encode(array_column($monthly_revenue, 'revenue')); ?>,
                borderColor: '#D4A017',
                backgroundColor: 'rgba(212, 160, 23, 0.1)',
                borderWidth: 3,
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return '₦' + context.parsed.y.toLocaleString();
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return '₦' + value.toLocaleString();
                        }
                    }
                }
            }
        }
    });
    
    // Application Status Chart
    const applicationCtx = document.getElementById('applicationChart').getContext('2d');
    const applicationData = <?php echo json_encode($application_stats); ?>;
    
    const applicationChart = new Chart(applicationCtx, {
        type: 'doughnut',
        data: {
            labels: applicationData.map(item => item.status.replace('_', ' ').toUpperCase()),
            datasets: [{
                data: applicationData.map(item => item.count),
                backgroundColor: [
                    '#ffc107',
                    '#28a745',
                    '#dc3545',
                    '#17a2b8',
                    '#6c757d'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
</script>

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