<?php 
include('header.php');

// Fetch manual services WITH COUNTS
$manualServices = [];
$servicesQuery = mysqli_query($ahk_conn, "SELECT * FROM service_management WHERE status='YES' ORDER BY sort_order ASC");
while($svc = mysqli_fetch_assoc($servicesQuery)) {
    $userColumn = $svc['user_column'];
    if (isset($udata[$userColumn]) && $udata[$userColumn] == 'YES') {
        $tableName = '';
        $totalCount = 0;
        $todayCount = 0;
        $pendingCount = 0;
        $successCount = 0;
        
        switch($svc['service_key']) {
            case 'll_apply_fee': $tableName = 'll_requests'; break;
            case 'puc_bike_fee': case 'puc_car_fee': $tableName = 'puc_requests'; break;
            case 'voter_direct_pdf_fee': $tableName = 'voter_direct_pdf_requests'; break;
            case 'voter_mobile_link_fee': $tableName = 'voter_mobile_link_requests'; break;
            case 'dl_to_mobile_fee': $tableName = 'dl_to_mobile_requests'; break;
            case 'pan_aadhaar_otp_fee': $tableName = 'pan_aadhaar_otp_requests'; break;
            case 'tec_exam_fee': $tableName = 'tec_exam_requests'; break;
            case 'mobile_lookup_fee': case 'aadhaar_lookup_fee': $tableName = 'lookup_history'; break;
        }
        
        if(!empty($tableName)) {
            if($tableName == 'lookup_history') {
                $lookupType = ($svc['service_key'] == 'mobile_lookup_fee') ? 'mobile' : 'aadhaar';
                $totalCount = mysqli_num_rows(mysqli_query($ahk_conn, "SELECT id FROM $tableName WHERE lookup_type='$lookupType'"));
                $todayCount = mysqli_num_rows(mysqli_query($ahk_conn, "SELECT id FROM $tableName WHERE lookup_type='$lookupType' AND DATE(date_time)=CURDATE()"));
            } else {
                $totalCount = mysqli_num_rows(mysqli_query($ahk_conn, "SELECT id FROM $tableName"));
                $todayCount = mysqli_num_rows(mysqli_query($ahk_conn, "SELECT id FROM $tableName WHERE DATE(request_date)=CURDATE()"));
                $pendingCount = mysqli_num_rows(mysqli_query($ahk_conn, "SELECT id FROM $tableName WHERE status='Pending'"));
                $successCount = mysqli_num_rows(mysqli_query($ahk_conn, "SELECT id FROM $tableName WHERE status='Completed'"));
            }
        }
        
        $svc['total_count'] = $totalCount;
        $svc['today_count'] = $todayCount;
        $svc['pending_count'] = $pendingCount;
        $svc['success_count'] = $successCount;
        
        $manualServices[] = $svc;
    }
}

$unreadNews = mysqli_num_rows(mysqli_query($ahk_conn, "SELECT id FROM admin_news WHERE status='active' AND DATE(created_at) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)"));
?>

<style>
body { background: #f4f6f9; }
.page-content { padding: 20px; }

.stat-card {
    background: #fff;
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    margin-bottom: 20px;
}
.stat-card h3 { margin: 0; font-size: 28px; font-weight: 700; }
.stat-card p { margin: 5px 0 0; color: #666; font-size: 14px; }

.news-alert {
    background: #fff3cd;
    border: 1px solid #ffc107;
    border-radius: 8px;
    padding: 15px 20px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.news-alert a {
    background: #ffc107;
    color: #000;
    padding: 8px 20px;
    border-radius: 5px;
    text-decoration: none;
    font-weight: 600;
}

.contact-banner {
    background: #28a745;
    color: #fff;
    border-radius: 10px;
    padding: 20px;
    margin-bottom: 25px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.contact-banner h5 { margin: 0 0 5px; }
.contact-banner p { margin: 0; opacity: 0.9; }
.contact-banner a {
    background: #fff;
    color: #28a745;
    padding: 10px 20px;
    border-radius: 5px;
    text-decoration: none;
    font-weight: 600;
}

.section-box {
    background: #fff;
    border-radius: 10px;
    padding: 20px;
    margin-bottom: 25px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}
.section-title {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 2px solid #eee;
    color: #333;
}

.services-grid {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 15px;
}
@media (max-width: 1200px) { .services-grid { grid-template-columns: repeat(4, 1fr); } }
@media (max-width: 992px) { .services-grid { grid-template-columns: repeat(3, 1fr); } }
@media (max-width: 768px) { .services-grid { grid-template-columns: repeat(2, 1fr); } }

.service-card {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 10px;
    padding: 20px 15px;
    text-align: center;
    text-decoration: none;
    color: #333;
    transition: all 0.3s ease;
    display: block;
}
.service-card:hover {
    background: #667eea;
    color: #fff;
    transform: translateY(-3px);
    box-shadow: 0 5px 15px rgba(102,126,234,0.3);
}
.service-card:hover .service-icon { background: rgba(255,255,255,0.2); }
.service-card:hover .service-name { color: #fff; }

.service-icon {
    width: 60px;
    height: 60px;
    margin: 0 auto 12px;
    background: #fff;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2px 5px rgba(0,0,0,0.08);
}
.service-icon img { width: 40px; height: 40px; object-fit: contain; }
.service-name { font-size: 13px; font-weight: 600; color: #333; margin: 0; line-height: 1.3; }
.service-badge {
    display: inline-block;
    background: #dc3545;
    color: #fff;
    font-size: 10px;
    padding: 2px 8px;
    border-radius: 10px;
    margin-top: 8px;
}

.admin-section { background: linear-gradient(135deg, #667eea, #764ba2); }
.admin-section .section-title { color: #fff; border-bottom-color: rgba(255,255,255,0.2); }
.admin-card { background: rgba(255,255,255,0.95); }
.admin-card:hover { background: #fff; }
.admin-stats { display: flex; gap: 5px; justify-content: center; margin-top: 8px; flex-wrap: wrap; }
.admin-stats span { font-size: 9px; padding: 2px 6px; border-radius: 5px; background: #e9ecef; color: #666; }
</style>

<div class="page-wrapper">
    <div class="page-content">
        
        <?php if (checkAdmin($udata['type']) == true): ?>
        <div class="row mb-3">
            <div class="col-md-3 col-6">
                <div class="stat-card">
                    <h3><?php echo $allusersforadmin ?? 0; ?></h3>
                    <p><i class="fas fa-users text-primary"></i> Total Users</p>
                </div>
            </div>
            <div class="col-md-3 col-6">
                <div class="stat-card">
                    <?php
                    $buttonText = "Check Balance";
                    if (isset($_POST['check_balance'])) {
                        $apiUrl = "https://" . htmlspecialchars($flexsecureapiurl) . "/api/v1/Balance_info?apiKey=" . urlencode($flexsecure_key);
                        $ch = curl_init();
                        curl_setopt($ch, CURLOPT_URL, $apiUrl);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
                        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
                        $responseApi = curl_exec($ch);
                        if (!curl_errno($ch)) {
                            $response = json_decode($responseApi, true);
                            $buttonText = ($response['status'] === "success") ? "₹" . htmlspecialchars($response['balance']) : "Error";
                        }
                        curl_close($ch);
                    }
                    ?>
                    <form method="POST" class="mb-0">
                        <button type="submit" name="check_balance" class="btn btn-primary w-100"><?php echo $buttonText; ?></button>
                    </form>
                    <p class="mt-2"><i class="fas fa-wallet text-success"></i> API Balance</p>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <?php if($unreadNews > 0): ?>
        <div class="news-alert">
            <div><i class="fas fa-bell text-warning"></i> <strong>New Updates!</strong> You have <?php echo $unreadNews; ?> unread news.</div>
            <a href="news_updates.php"><i class="fas fa-newspaper"></i> View News</a>
        </div>
        <?php endif; ?>

        <div class="contact-banner">
            <div>
                <h5>📞 Customer Support</h5>
                <p>Hello <?php echo $udata['name']; ?>, Need help? Contact us!</p>
            </div>
            <a href="https://wa.me/<?php echo ahkweb('phone'); ?>" target="_blank"><i class="fab fa-whatsapp"></i> WhatsApp</a>
        </div>

        <div class="section-box">
            <div class="section-title">📱 All Services</div>
            <div class="services-grid">
                <?php
                $coreServices = [
                    ["name" => "Aadhaar Services", "link" => "Uid_Flx-Services", "icon" => "../images/aadhaar_icon.jpg"],
                    ["name" => "Pan Card Services", "link" => "pan_card_service", "icon" => "../admin/uploads/Services/panservices.png"],
                    ["name" => "Vehicle Services", "link" => "vahicle_card_service", "icon" => "../admin/uploads/Services/Yamaha-Bike-PNG.png"],
                    ["name" => "Voter Services", "link" => "Voter_card_service", "icon" => "../admin/uploads/Services/voter.png"],
                    ["name" => "Ration Services", "link" => "Ration_card_service", "icon" => "../admin/uploads/Services/ration1.png"],
                    ["name" => "Electric Bill", "link" => "ElectriBill_card_service", "icon" => "../admin/uploads/Services/electricBill.png"],
                    ["name" => "Farmer Services", "link" => "FarmerStackService", "icon" => "../admin/uploads/Services/farmerLogo0.png"],
                    ["name" => "Passbook Services", "link" => "Passbook_card_service", "icon" => "../admin/uploads/Services/1771198.png"],
                    ["name" => "Other Services", "link" => "Other_card_service", "icon" => "../admin/uploads/Services/dlpng.png"],
                ];
                foreach ($coreServices as $s):
                ?>
                <a href="<?php echo $s['link']; ?>" class="service-card">
                    <div class="service-icon"><img src="<?php echo $s['icon']; ?>" alt="<?php echo $s['name']; ?>"></div>
                    <p class="service-name"><?php echo $s['name']; ?></p>
                </a>
                <?php endforeach; ?>
            </div>
        </div>

        <?php if (!empty($manualServices)): ?>
        <div class="section-box">
            <div class="section-title">⚡ Premium Services</div>
            <div class="services-grid">
                <?php
                $serviceInfo = [
                    'll_apply_fee' => ['name' => 'LL Exam Pass', 'icon' => 'https://cdn-icons-png.flaticon.com/512/3097/3097180.png'],
                    'mobile_lookup_fee' => ['name' => 'Mobile Details', 'icon' => 'https://cdn-icons-png.flaticon.com/512/455/455705.png'],
                    'aadhaar_lookup_fee' => ['name' => 'Aadhaar To SIM', 'icon' => 'https://cdn-icons-png.flaticon.com/512/2920/2920235.png'],
                    'voter_direct_pdf_fee' => ['name' => 'Voter PDF', 'icon' => 'https://cdn-icons-png.flaticon.com/512/1034/1034131.png'],
                    'voter_mobile_link_fee' => ['name' => 'Voter Mobile', 'icon' => 'https://cdn-icons-png.flaticon.com/512/6614/6614887.png'],
                    'puc_bike_fee' => ['name' => 'PUC Certificate', 'icon' => 'https://cdn-icons-png.flaticon.com/512/2972/2972185.png'],
                    'dl_to_mobile_fee' => ['name' => 'DL to Mobile', 'icon' => 'https://cdn-icons-png.flaticon.com/512/3097/3097239.png'],
                    'pan_aadhaar_otp_fee' => ['name' => 'PAN by Aadhaar', 'icon' => 'https://cdn-icons-png.flaticon.com/512/4697/4697268.png'],
                    'tec_exam_fee' => ['name' => 'TEC Certificate', 'icon' => 'https://cdn-icons-png.flaticon.com/512/3976/3976625.png'],
                ];
                foreach($manualServices as $svc):
                    $info = $serviceInfo[$svc['service_key']] ?? ['name' => $svc['display_name'], 'icon' => $svc['icon_path']];
                ?>
                <a href="<?php echo $svc['dashboard_link']; ?>" class="service-card">
                    <div class="service-icon"><img src="<?php echo $info['icon']; ?>" alt="<?php echo $info['name']; ?>"></div>
                    <p class="service-name"><?php echo $info['name']; ?></p>
                    <?php if($svc['pending_count'] > 0): ?>
                    <span class="service-badge"><?php echo $svc['pending_count']; ?> Pending</span>
                    <?php endif; ?>
                </a>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <?php if (checkAdmin($udata['type']) == true && !empty($manualServices)): ?>
        <div class="section-box admin-section">
            <div class="section-title">⚙️ Admin Panel</div>
            <div class="services-grid">
                <a href="service_management" class="service-card admin-card">
                    <div class="service-icon"><i class="fas fa-sliders-h" style="font-size:28px;color:#667eea;"></i></div>
                    <p class="service-name">Service Management</p>
                </a>
                <?php
                $iconMap = ['ll_apply_fee'=>'fa-car','puc_bike_fee'=>'fa-certificate','voter_direct_pdf_fee'=>'fa-vote-yea','voter_mobile_link_fee'=>'fa-mobile-alt','dl_to_mobile_fee'=>'fa-id-card','pan_aadhaar_otp_fee'=>'fa-file-invoice','tec_exam_fee'=>'fa-graduation-cap','mobile_lookup_fee'=>'fa-phone','aadhaar_lookup_fee'=>'fa-fingerprint'];
                foreach($manualServices as $svc):
                    $adminLink = str_replace('.php', '_admin.php', $svc['sidebar_link']);
                    $icon = $iconMap[$svc['service_key']] ?? 'fa-tasks';
                ?>
                <a href="<?php echo $adminLink; ?>" class="service-card admin-card">
                    <div class="service-icon"><i class="fas <?php echo $icon; ?>" style="font-size:28px;color:#28a745;"></i></div>
                    <p class="service-name"><?php echo str_replace(' Request', '', $svc['display_name']); ?></p>
                    <div class="admin-stats">
                        <?php if($svc['total_count'] > 0): ?><span>Total: <?php echo $svc['total_count']; ?></span><?php endif; ?>
                        <?php if($svc['pending_count'] > 0): ?><span style="background:#ffc107;color:#000;">Pending: <?php echo $svc['pending_count']; ?></span><?php endif; ?>
                    </div>
                </a>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

    </div>
</div>

<?php include('../admin/footers.php'); ?>
<script src="../template/ahkweb/assets/js/bootstrap.bundle.min.js"></script>
<script src="../template/ahkweb/assets/js/jquery.min.js"></script>
<script src="../template/ahkweb/assets/plugins/simplebar/js/simplebar.min.js"></script>
<script src="../template/ahkweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/ahkweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../template/ahkweb/assets/js/app.js"></script>
</body>
</html>