<?php
/**
 * ============================================================================
 * admin/index.php - Admin Dashboard
 * ============================================================================
 */

if (!defined('AIMS_ACCESS')) {
    define('AIMS_ACCESS', true);
}

require_once '../config/config.php';

// Check if user is logged in and is admin
if (!isLoggedIn() || getUserType() !== 'admin') {
    header('Location: ../auth/login.php');
    exit();
}

$userId = getUserId();
$userName = getUserName();

$database = new Database();
$db = $database->getConnection();

// Fetch admin statistics
$stats = [];

// Total Users by Type
$sql = "SELECT user_type, COUNT(*) as count FROM users GROUP BY user_type";
$stmt = $db->query($sql);
$userStats = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($userStats as $stat) {
    $stats['users_' . $stat['user_type']] = $stat['count'];
}

// Total Users
$sql = "SELECT COUNT(*) as total FROM users";
$stmt = $db->query($sql);
$stats['total_users'] = $stmt->fetch()['total'] ?? 0;

// Pending Approvals
$sql = "SELECT COUNT(*) as total FROM user_approvals WHERE approval_status = 'pending'";
$stmt = $db->query($sql);
$stats['pending_approvals'] = $stmt->fetch()['total'] ?? 0;

// Total Products
$sql = "SELECT COUNT(*) as total FROM products";
$stmt = $db->query($sql);
$stats['total_products'] = $stmt->fetch()['total'] ?? 0;

// Active Products
$sql = "SELECT COUNT(*) as total FROM products WHERE status = 'available'";
$stmt = $db->query($sql);
$stats['active_products'] = $stmt->fetch()['total'] ?? 0;

// Total Orders
$sql = "SELECT COUNT(*) as total FROM orders";
$stmt = $db->query($sql);
$stats['total_orders'] = $stmt->fetch()['total'] ?? 0;

// Recent Users
$sql = "SELECT * FROM users ORDER BY created_at DESC LIMIT 5";
$stmt = $db->query($sql);
$recentUsers = $stmt->fetchAll();

// Pending Approvals
$sql = "SELECT ua.*, u.full_name, u.phone_number, u.email 
        FROM user_approvals ua 
        JOIN users u ON ua.user_id = u.id 
        WHERE ua.approval_status = 'pending' 
        ORDER BY ua.created_at DESC LIMIT 5";
$stmt = $db->query($sql);
$pendingApprovals = $stmt->fetchAll();

// Recent Reports
$sql = "SELECT r.*, u.full_name as reporter_name 
        FROM reports r 
        JOIN users u ON r.reporter_id = u.id 
        WHERE r.status = 'pending' 
        ORDER BY r.created_at DESC LIMIT 5";
$stmt = $db->query($sql);
$recentReports = $stmt->fetchAll();

$pageTitle = 'Admin Dashboard - AIMS';
require_once '../includes/meta.php';
?>

<style>
    .stat-card {
        border-radius: 15px;
        transition: all 0.3s ease;
        border: none;
    }
    
    .stat-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 25px rgba(0,0,0,0.1);
    }
    
    .stat-icon {
        width: 60px;
        height: 60px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.8rem;
    }
    
    .admin-sidebar {
        position: fixed;
        left: 0;
        top: 60px;
        height: calc(100vh - 60px);
        width: 250px;
        background: white;
        border-right: 1px solid #e5e7eb;
        overflow-y: auto;
        z-index: 100;
    }
    
    .admin-content {
        margin-left: 250px;
        padding: 20px;
    }
    
    .nav-link {
        color: #6b7280;
        padding: 12px 20px;
        display: flex;
        align-items: center;
        text-decoration: none;
        transition: all 0.3s ease;
    }
    
    .nav-link:hover {
        background-color: #f3f4f6;
        color: var(--primary-color);
    }
    
    .nav-link.active {
        background-color: #dcfce7;
        color: var(--primary-color);
        border-right: 3px solid var(--primary-color);
    }
    
    .nav-link i {
        margin-right: 10px;
        width: 20px;
        text-align: center;
    }
    
    @media (max-width: 768px) {
        .admin-sidebar {
            transform: translateX(-100%);
            transition: transform 0.3s ease;
        }
        
        .admin-sidebar.show {
            transform: translateX(0);
        }
        
        .admin-content {
            margin-left: 0;
        }
    }
</style>
</head>
<body>

<?php require_once '../includes/header.php'; ?>

<!-- Admin Sidebar -->
<div class="admin-sidebar">
    <div class="p-3 border-bottom">
        <h6 class="mb-0 fw-bold">Admin Panel</h6>
    </div>
    <nav class="nav flex-column">
        <a href="index.php" class="nav-link active">
            <i class="bi bi-speedometer2"></i> Dashboard
        </a>
        <a href="approvals.php" class="nav-link">
            <i class="bi bi-check-circle"></i> Approvals
            <?php if ($stats['pending_approvals'] > 0): ?>
                <span class="badge bg-danger ms-auto"><?php echo $stats['pending_approvals']; ?></span>
            <?php endif; ?>
        </a>
        <a href="users.php" class="nav-link">
            <i class="bi bi-people"></i> Users
        </a>
        <a href="locations.php" class="nav-link">
            <i class="bi bi-geo-alt"></i> Locations
        </a>
        <a href="products.php" class="nav-link">
            <i class="bi bi-box-seam"></i> Products
        </a>
        <a href="orders.php" class="nav-link">
            <i class="bi bi-cart"></i> Orders
        </a>
        <a href="market-prices.php" class="nav-link">
            <i class="bi bi-graph-up"></i> Market Prices
        </a>
        <a href="tips.php" class="nav-link">
            <i class="bi bi-lightbulb"></i> Agricultural Tips
        </a>
        <a href="reports.php" class="nav-link">
            <i class="bi bi-flag"></i> Reports
        </a>
        <a href="settings.php" class="nav-link">
            <i class="bi bi-gear"></i> Settings
        </a>
    </nav>
</div>

<!-- Admin Content -->
<div class="admin-content">
    <!-- Welcome Section -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                <div class="card-body text-white p-4">
                    <h3 class="mb-2 fw-bold">Welcome, <?php echo htmlspecialchars($userName); ?>! 👨‍💼</h3>
                    <p class="mb-0 opacity-90">Manage your agricultural platform</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card stat-card shadow-sm">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1 small">Total Users</p>
                            <h3 class="mb-0 fw-bold"><?php echo $stats['total_users']; ?></h3>
                        </div>
                        <div class="stat-icon bg-primary bg-opacity-10 text-primary">
                            <i class="bi bi-people"></i>
                        </div>
                    </div>
                    <div class="mt-2">
                        <small class="text-muted">
                            <?php echo $stats['users_farmer'] ?? 0; ?> Farmers • 
                            <?php echo $stats['users_buyer'] ?? 0; ?> Buyers
                        </small>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card stat-card shadow-sm">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1 small">Pending Approvals</p>
                            <h3 class="mb-0 fw-bold"><?php echo $stats['pending_approvals']; ?></h3>
                        </div>
                        <div class="stat-icon bg-warning bg-opacity-10 text-warning">
                            <i class="bi bi-hourglass-split"></i>
                        </div>
                    </div>
                    <div class="mt-2">
                        <a href="approvals.php" class="btn btn-sm btn-warning">Review Now</a>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card stat-card shadow-sm">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1 small">Total Products</p>
                            <h3 class="mb-0 fw-bold"><?php echo $stats['total_products']; ?></h3>
                        </div>
                        <div class="stat-icon bg-success bg-opacity-10 text-success">
                            <i class="bi bi-box-seam"></i>
                        </div>
                    </div>
                    <div class="mt-2">
                        <small class="text-success"><?php echo $stats['active_products']; ?> active</small>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card stat-card shadow-sm">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1 small">Total Orders</p>
                            <h3 class="mb-0 fw-bold"><?php echo $stats['total_orders']; ?></h3>
                        </div>
                        <div class="stat-icon bg-info bg-opacity-10 text-info">
                            <i class="bi bi-cart"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- Pending Approvals -->
        <div class="col-lg-6 mb-4">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-0 py-3 d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 fw-bold">
                        <i class="bi bi-clock-history text-warning me-2"></i>Pending Approvals
                    </h5>
                    <a href="approvals.php" class="btn btn-sm btn-outline-primary">View All</a>
                </div>
                <div class="card-body">
                    <?php if (empty($pendingApprovals)): ?>
                        <div class="text-center py-4 text-muted">
                            <i class="bi bi-check-circle fs-1"></i>
                            <p class="mb-0 mt-2">No pending approvals</p>
                        </div>
                    <?php else: ?>
                        <div class="list-group list-group-flush">
                            <?php foreach ($pendingApprovals as $approval): ?>
                            <div class="list-group-item px-0">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <h6 class="mb-1"><?php echo htmlspecialchars($approval['full_name']); ?></h6>
                                        <p class="mb-1 small text-muted">
                                            <i class="bi bi-briefcase me-1"></i><?php echo ucfirst($approval['user_type']); ?>
                                        </p>
                                        <small class="text-muted">
                                            <i class="bi bi-clock me-1"></i><?php echo timeAgo($approval['created_at']); ?>
                                        </small>
                                    </div>
                                    <a href="approval-details.php?id=<?php echo $approval['id']; ?>" class="btn btn-sm btn-primary">
                                        Review
                                    </a>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Recent Users -->
        <div class="col-lg-6 mb-4">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-0 py-3 d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 fw-bold">
                        <i class="bi bi-person-plus text-success me-2"></i>Recent Users
                    </h5>
                    <a href="users.php" class="btn btn-sm btn-outline-primary">View All</a>
                </div>
                <div class="card-body">
                    <div class="list-group list-group-flush">
                        <?php foreach ($recentUsers as $user): ?>
                        <div class="list-group-item px-0">
                            <div class="d-flex justify-content-between align-items-start">
                                <div>
                                    <h6 class="mb-1"><?php echo htmlspecialchars($user['full_name']); ?></h6>
                                    <p class="mb-1 small text-muted">
                                        <i class="bi bi-phone me-1"></i><?php echo $user['phone_number']; ?>
                                    </p>
                                    <span class="badge bg-<?php echo $user['user_type'] === 'farmer' ? 'success' : 'primary'; ?>">
                                        <?php echo ucfirst($user['user_type']); ?>
                                    </span>
                                </div>
                                <small class="text-muted">
                                    <?php echo timeAgo($user['created_at']); ?>
                                </small>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Recent Reports -->
    <?php if (!empty($recentReports)): ?>
    <div class="row">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-0 py-3 d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 fw-bold">
                        <i class="bi bi-flag text-danger me-2"></i>Recent Reports
                    </h5>
                    <a href="reports.php" class="btn btn-sm btn-outline-primary">View All</a>
                </div>
                <div class="card-body">
                    <div class="list-group list-group-flush">
                        <?php foreach ($recentReports as $report): ?>
                        <div class="list-group-item px-0">
                            <div class="d-flex justify-content-between align-items-start">
                                <div class="flex-grow-1">
                                    <h6 class="mb-1"><?php echo ucfirst($report['report_type']); ?> Report</h6>
                                    <p class="mb-1 small"><?php echo htmlspecialchars(substr($report['reason'], 0, 100)); ?>...</p>
                                    <small class="text-muted">
                                        Reported by: <?php echo htmlspecialchars($report['reporter_name']); ?> • 
                                        <?php echo timeAgo($report['created_at']); ?>
                                    </small>
                                </div>
                                <a href="report-details.php?id=<?php echo $report['id']; ?>" class="btn btn-sm btn-outline-danger">
                                    Review
                                </a>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

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