<?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;
    }
}

// Check unread news
$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)"));
?>

<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&family=Nunito:wght@500;700&display=swap" rel="stylesheet">

<style>
body { background: #f5f7fa; font-family: 'Inter', sans-serif; color: #333; }
h1, h2, h3, .service-title { font-family: 'Nunito', sans-serif; font-weight: 700; color: #222; }

.dashboard-card {
  border-radius: 14px;
  background: #fff;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
  padding: 1.2rem;
  transition: all 0.3s ease;
}
.dashboard-card:hover { transform: translateY(-6px); box-shadow: 0 10px 22px rgba(0,0,0,0.12); }
.card-icon { font-size: 34px; color: #007bff; }
.small-title { font-size: 14px; font-weight: 600; opacity: 0.7; }
.metric-value { font-size: 24px; font-weight: 700; }

.news-alert-btn {
  background: linear-gradient(135deg, #f093fb, #f5576c);
  color: white;
  border: none;
  padding: 15px 40px;
  border-radius: 50px;
  font-size: 18px;
  font-weight: 700;
  box-shadow: 0 10px 30px rgba(245, 87, 108, 0.4);
  animation: bounce 2s infinite;
  cursor: pointer;
  text-decoration: none;
  display: inline-block;
  margin: 30px 0;
}
.news-alert-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 15px 40px rgba(245, 87, 108, 0.6);
}
@keyframes bounce {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-10px); }
}

.contact-banner {
  border-radius: 12px;
  padding: 18px;
  display: flex;
  align-items: center;
  gap: 18px;
  background: linear-gradient(120deg,#09a30b 0%, #10b31e 60%);
  color: #fff;
  box-shadow: 0 8px 20px rgba(0,0,0,0.10);
  margin-bottom: 30px;
}

.services-box {
  background: white;
  border-radius: 15px;
  padding: 30px 20px;
  margin-bottom: 30px;
  box-shadow: 0 4px 15px rgba(0,0,0,0.08);
}

.box-header {
  text-align: center;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 3px solid #667eea;
}

.col-custom-5 {
  flex: 0 0 20%;
  max-width: 20%;
  padding: 10px;
}
@media (max-width: 1200px) { .col-custom-5 { flex: 0 0 25%; max-width: 25%; } }
@media (max-width: 992px) { .col-custom-5 { flex: 0 0 33.33%; max-width: 33.33%; } }
@media (max-width: 768px) { .col-custom-5 { flex: 0 0 50%; max-width: 50%; } }
@media (max-width: 576px) { .col-custom-5 { flex: 0 0 100%; max-width: 100%; } }

.service-card {
  border-radius: 14px;
  background: #fff;
  border: 1px solid #eee;
  box-shadow: 0 4px 10px rgba(0,0,0,0.05);
  padding: 20px;
  height: 240px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  transition: all 0.25s ease;
  position: relative;
  text-align: center;
}
.service-card:hover {
  transform: translateY(-8px);
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  box-shadow: 0 10px 25px rgba(102, 126, 234, 0.4);
}
.service-card:hover .service-title { color: #fff; }
.service-card:hover .service-icon { background: rgba(255,255,255,0.2); }
.service-card:hover .count-badge { background: rgba(255,255,255,0.9); color: #667eea; }

.service-icon {
  width: 90px;
  height: 90px;
  border-radius: 16px;
  background: #f0f4ff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 12px;
}
.service-icon img { width: 70px; height: 70px; object-fit: contain; }
.service-title { font-size: 0.95rem; font-weight: 600; color: #222; margin-bottom: 8px; }
.count-badge {
  background: #667eea;
  color: white;
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 600;
  display: inline-flex;
  align-items: center;
  gap: 5px;
}
.admin-stats {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: center;
  margin-top: 8px;
}
.stat-mini {
  background: rgba(102,126,234,0.1);
  padding: 3px 8px;
  border-radius: 8px;
  font-size: 10px;
  font-weight: 600;
}
</style>

<div class="page-wrapper">
  <div class="page-content">
    
    <?php if (checkAdmin($udata['type']) == true): ?>
    <div class="row g-3 mb-4">
        <?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)) {
                $buttonText = "Error: " . curl_error($ch);
            } else {
                $response = json_decode($responseApi, true);
                $buttonText = ($response['status'] === "success") 
                    ? "₹ " . htmlspecialchars($response['balance']) 
                    : "Error";
            }
            curl_close($ch);
        }
        ?>
        <div class="col-lg-3 col-md-6">
          <div class="dashboard-card">
            <div class="d-flex justify-content-between align-items-center">
              <div>
                <div class="small-title">Total Users</div>
                <div class="metric-value"><?php echo $allusersforadmin; ?></div>
              </div>
              <i class="bx bx-user card-icon"></i>
            </div>
          </div>
        </div>
        
        <div class="col-lg-3 col-md-6">
          <div class="dashboard-card">
            <form method="POST">
              <div class="d-flex justify-content-between align-items-center mb-2">
                <div class="small-title">API Balance</div>
                <i class="bx bx-wallet card-icon"></i>
              </div>
              <button type="submit" name="check_balance" class="btn btn-primary btn-sm w-100">
                <?php echo $buttonText; ?>
              </button>
            </form>
          </div>
        </div>
    </div>
    <?php endif; ?>

    <?php if($unreadNews > 0): ?>
    <div class="text-center">
      <a href="news_updates" class="news-alert-btn">
        <i class="fas fa-newspaper"></i> 📢 Today News - Click Here! (<?php echo $unreadNews; ?> New)
      </a>
    </div>
    <?php endif; ?>

    <div class="container-fluid">
      <div class="contact-banner">
        <div style="flex:1;">
          <div style="font-weight:800;font-size:18px;">📞 Customer Care</div>
          <div style="font-size:14px;margin:8px 0;">Hello <strong><?php echo $udata['name']; ?></strong></div>
          <div style="margin-top:12px;display:flex;gap:10px;flex-wrap:wrap;">
            <a style="display:inline-flex;align-items:center;gap:8px;background:rgba(0,0,0,0.06);padding:6px 10px;border-radius:10px;color:#fff;text-decoration:none;font-weight:700;" href="https://wa.me/<?php echo ahkweb('phone'); ?>" target="_blank">
              <img src="/assets/img/whatsapp_icon.png" style="width:22px;" alt="WA">
              <span><?php echo ahkweb('phone'); ?></span>
            </a>
          </div>
        </div>
        <div style="width:170px;height:120px;border-radius:10px;overflow:hidden;">
          <img src="/assets/img/care.jpg" style="width:100%;height:100%;object-fit:contain;">
        </div>
      </div>
    </div>

    <!-- BOX 1: Core Services -->
    <div class="services-box">
      <div class="box-header">
        <h2>📱 All Services</h2>
        <p style="margin:0;color:#666;">✅ Reliable | 🔒 Secure | 🚀 Fast</p>
      </div>

      <div class="row g-3">
        <?php
        $coreServices = [
            ["name" => "Aadhaar Services", "link" => "Uid_Flx-Services", "icon" => "../images/aadhaar_icon.jpg"],
            ["name" => "Pan 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):
        ?>
          <div class="col-custom-5">
            <a href="<?php echo $s['link']; ?>" class="text-decoration-none">
              <div class="service-card">
                <div class="service-icon">
                  <img src="<?php echo $s['icon']; ?>" alt="<?php echo $s['name']; ?>">
                </div>
                <div class="service-title"><?php echo $s['name']; ?></div>
              </div>
            </a>
          </div>
        <?php endforeach; ?>
      </div>
    </div>

    <!-- BOX 2: Premium Services -->
    <?php if (!empty($manualServices)): ?>
    <div class="services-box">
      <div class="box-header">
        <h2>⚡ Premium Direct Services</h2>
        <p style="margin:0;color:#666;">🚀 Fast Processing | 📋 Manual Verification</p>
      </div>

      <div class="row g-3">
        <?php
        $serviceInfo = [
            'll_apply_fee' => ['name' => 'LL Exam Pass Request', 'icon' => 'https://cdn-icons-png.flaticon.com/512/3097/3097180.png'],
            'mobile_lookup_fee' => ['name' => 'Mobile To All Details', 'icon' => 'https://cdn-icons-png.flaticon.com/512/455/455705.png'],
            'aadhaar_lookup_fee' => ['name' => 'Aadhaar To All SIM', 'icon' => 'https://cdn-icons-png.flaticon.com/512/2920/2920235.png'],
            'voter_direct_pdf_fee' => ['name' => 'Voter Direct PDF', 'icon' => 'https://cdn-icons-png.flaticon.com/512/1034/1034131.png'],
            'voter_mobile_link_fee' => ['name' => 'Voter Mobile Link', '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 Exam 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']];
        ?>
          <div class="col-custom-5">
            <a href="<?php echo $svc['dashboard_link']; ?>" class="text-decoration-none">
              <div class="service-card">
                <div class="service-icon">
                  <img src="<?php echo $info['icon']; ?>" alt="<?php echo $info['name']; ?>">
                </div>
                <div class="service-title"><?php echo $info['name']; ?></div>
                <?php if($svc['pending_count'] > 0): ?>
                  <div class="count-badge">
                    <i class="fas fa-clock"></i> <?php echo $svc['pending_count']; ?> Pending
                  </div>
                <?php elseif($svc['today_count'] > 0): ?>
                  <div class="count-badge">
                    <i class="fas fa-calendar-day"></i> <?php echo $svc['today_count']; ?> Today
                  </div>
                <?php endif; ?>
              </div>
            </a>
          </div>
        <?php endforeach; ?>
        
        <div class="col-custom-5">
          <a href="../admin/upcoming.php" class="text-decoration-none">
            <div class="service-card" style="background:linear-gradient(135deg,#f093fb,#f5576c);color:#fff;">
              <div class="service-icon" style="background:rgba(255,255,255,0.2);">
                <i class="fas fa-rocket" style="font-size:50px;color:#fff;"></i>
              </div>
              <div class="service-title" style="color:#fff;">More Services Soon!</div>
            </div>
          </a>
        </div>
      </div>
    </div>
    <?php endif; ?>

    <!-- BOX 3: Admin Panel -->
    <?php if (checkAdmin($udata['type']) == true && !empty($manualServices)): ?>
    <div class="services-box" style="background:linear-gradient(135deg,#667eea,#764ba2);">
      <div class="box-header" style="border-bottom-color:rgba(255,255,255,0.3);">
        <h2 style="color:#fff;">⚙️ Admin Management</h2>
        <p style="color:rgba(255,255,255,0.9);margin:0;">🔐 Manage Services</p>
      </div>

      <div class="row g-3">
        <div class="col-custom-5">
          <a href="service_management" class="text-decoration-none">
            <div class="service-card" style="background:rgba(255,255,255,0.95);height:220px;">
              <div class="service-icon">
                <i class="fas fa-sliders-h" style="font-size:50px;color:#667eea;"></i>
              </div>
              <div class="service-title">Service Management</div>
            </div>
          </a>
        </div>

        <?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';
        ?>
          <div class="col-custom-5">
            <a href="<?php echo $adminLink; ?>" class="text-decoration-none">
              <div class="service-card" style="background:rgba(255,255,255,0.95);height:220px;">
                <div class="service-icon">
                  <i class="fas <?php echo $icon; ?>" style="font-size:50px;color:#28a745;"></i>
                </div>
                <div class="service-title"><?php echo str_replace(' Request', '', $svc['display_name']); ?></div>
                <div class="admin-stats">
                  <?php if($svc['total_count'] > 0): ?>
                    <span class="stat-mini">📊 Total: <?php echo $svc['total_count']; ?></span>
                  <?php endif; ?>
                  <?php if($svc['today_count'] > 0): ?>
                    <span class="stat-mini">📅 Today: <?php echo $svc['today_count']; ?></span>
                  <?php endif; ?>
                  <?php if($svc['pending_count'] > 0): ?>
                    <span class="stat-mini" style="background:rgba(255,75,43,0.2);color:#ff4b2b;">⏳ Pending: <?php echo $svc['pending_count']; ?></span>
                  <?php endif; ?>
                  <?php if($svc['success_count'] > 0): ?>
                    <span class="stat-mini" style="background:rgba(40,167,69,0.2);color:#28a745;">✅ Done: <?php echo $svc['success_count']; ?></span>
                  <?php endif; ?>
                </div>
              </div>
            </a>
          </div>
        <?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>