<?php
checkSession();

$activeManualServices = [];
$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') {
        $activeManualServices[] = $svc;
    }
}

// Check for 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)"));

// Get unread messages count
if(checkAdmin($udata['type'])) {
    $unreadMessages = mysqli_num_rows(mysqli_query($ahk_conn, "SELECT id FROM contact WHERE is_read=0"));
} else {
    $unreadMessages = mysqli_num_rows(mysqli_query($ahk_conn, "SELECT id FROM contact WHERE email='".$udata['email']."' AND reply IS NOT NULL AND is_read_user=0"));
}
?>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" type="image/x-icon" href="<?php echo ahkweb('logo');  ?>">
    <link href="../template/ahkweb/assets/plugins/simplebar/css/simplebar.css" rel="stylesheet" />
    <link href="../template/ahkweb/assets/plugins/perfect-scrollbar/css/perfect-scrollbar.css" rel="stylesheet" />
    <link href="../template/ahkweb/assets/plugins/metismenu/css/metisMenu.min.css" rel="stylesheet" />
    <link href="../template/ahkweb/assets/css/pace.min.css" rel="stylesheet" />
    <script src="../template/ahkweb/assets/js/pace.min.js"></script>
    <link href="../template/ahkweb/assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="../template/ahkweb/assets/css/bootstrap-extended.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap" rel="stylesheet">
    <link href="../template/ahkweb/assets/css/app.css" rel="stylesheet">
    <link href="../template/ahkweb/assets/css/icons.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <title>Dashboard | <?php echo ahkweb('webname'); ?></title>
    <style>
        .badge-instant {
            background-color: #28a745;
            color: white;
            font-size: 9px;
            padding: 2px 5px;
            border-radius: 6px;
            margin-left: 4px;
            font-weight: bold;
        }
        .badge-count {
            background: #ff4b2b;
            color: #fff;
            padding: 2px 6px;
            border-radius: 10px;
            font-size: 10px;
            margin-left: 5px;
        }
        .news-pulse {
            animation: pulse 1.5s infinite;
        }
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
        
        /* Theme Switcher Styles */
        .theme-switcher {
            position: fixed;
            top: 50%;
            right: 0;
            transform: translateY(-50%);
            z-index: 9999;
            background: white;
            border-radius: 10px 0 0 10px;
            box-shadow: -5px 0 15px rgba(0,0,0,0.2);
            padding: 15px 10px;
        }
        .theme-btn {
            display: block;
            width: 50px;
            height: 50px;
            border: none;
            border-radius: 10px;
            margin-bottom: 10px;
            cursor: pointer;
            font-size: 24px;
            transition: all 0.3s ease;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .theme-btn:hover {
            transform: scale(1.1);
        }
        .theme-btn.active {
            box-shadow: 0 0 0 3px #667eea;
        }
        .theme-day { background: linear-gradient(135deg, #ffeaa7, #fdcb6e); }
        .theme-night { background: linear-gradient(135deg, #2d3436, #000000); color: white; }
        .theme-bw { background: linear-gradient(135deg, #ffffff, #000000); color: #666; }
        
        /* Night Theme */
        body.night-theme {
            background: #1a1a2e !important;
            color: #eee !important;
        }
        .night-theme .sidebar-wrapper {
            background: #16213e !important;
        }
        .night-theme .topbar {
            background: #0f3460 !important;
        }
        .night-theme .card,
        .night-theme .dashboard-card,
        .night-theme .service-card,
        .night-theme .services-box {
            background: #16213e !important;
            color: #eee !important;
            border-color: #0f3460 !important;
        }
        .night-theme .page-content {
            background: #1a1a2e !important;
        }
        
        /* Black & White Theme */
        body.bw-theme * {
            filter: grayscale(100%) !important;
        }
        .bw-theme .service-card:hover {
            background: #333 !important;
        }
    </style>
</head>

<body class="day-theme">
    <!-- Theme Switcher -->
    <div class="theme-switcher">
        <button class="theme-btn theme-day active" onclick="setTheme('day')" title="Day Mode">
            ☀️
        </button>
        <button class="theme-btn theme-night" onclick="setTheme('night')" title="Night Mode">
            🌙
        </button>
        <button class="theme-btn theme-bw" onclick="setTheme('bw')" title="Black & White">
            ⚫
        </button>
    </div>

    <script>
        function setTheme(theme) {
            document.body.className = theme + '-theme';
            localStorage.setItem('portalTheme', theme);
            
            // Update active button
            document.querySelectorAll('.theme-btn').forEach(btn => btn.classList.remove('active'));
            document.querySelector('.theme-' + theme).classList.add('active');
        }
        
        // Load saved theme
        window.addEventListener('load', function() {
            const savedTheme = localStorage.getItem('portalTheme') || 'day';
            setTheme(savedTheme);
        });
    </script>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="wrapper">
        <div class="sidebar-wrapper" data-simplebar="true">
            <div class="sidebar-header">
                <div>
                    <img src="<?php echo ahkweb('logo'); ?>" class="logo-icon" alt="logo">
                </div>
                <div>
                    <h4 class="logo-text">
                        <?php
                        ob_start();
                        ahkweb('webname');
                        $webname = ob_get_clean();
                        $words = explode(' ', trim($webname));
                        echo isset($words[1]) ? $words[0] . ' ' . $words[1] : $words[0];
                        ?>
                    </h4>
                </div>
                <div class="toggle-icon ms-auto"><i class="bx bx-menu"></i></div>
            </div>

            <ul class="metismenu" id="menu">
                <li>
                    <a href="index">
                       <div class="parent-icon"><i class="text-danger fas fa-home"></i></div>
                        <div class="menu-title">Dashboard</div>
                    </a>
                </li>

                <?php if (checkAdmin($udata['type']) == true) { ?>
                    <li>
                        <a href="javascript:;" class="has-arrow">
                            <div class="parent-icon"><i class="fas fa-users text-primary"></i></div>
                            <div class="menu-title">User Management</div>
                        </a>
                        <ul>
                            <li><a href="users"><i class="bx bx-right-arrow-alt"></i>All Users</a></li>
                            <li><a href="adduser"><i class="bx bx-right-arrow-alt"></i>Add New</a></li>
                            <li><a href="qrpay_pending"><i class="bx bx-right-arrow-alt"></i>QR Pending</a></li>
                            <li><a href="PendingManualUsers"><i class="bx bx-right-arrow-alt"></i>Manual Pending</a></li>
                            <li><a href="BalanceTransfer"><i class="bx bx-right-arrow-alt"></i>Balance Transfer</a></li>
                        </ul>
                    </li>
                <?php } ?>

                <?php if ($udata['type'] == "distributor" || $udata['type'] == "super_dist") { ?>
                    <li>
                        <a href="javascript:;" class="has-arrow">
                            <div class="parent-icon"><i class="bx bx-user"></i></div>
                            <div class="menu-title">User Management</div>
                        </a>
                        <ul>
                            <li><a href="adduser"><i class="bx bx-right-arrow-alt"></i>Add New</a></li>
                            <li><a href="myusers"><i class="bx bx-right-arrow-alt"></i>My Users</a></li>
                        </ul>
                    </li>
                <?php } ?>

                <li>
                    <a href="wallet">
                        <div class="parent-icon"><i class="fas fa-wallet text-success"></i></div>
                        <div class="menu-title">Add Wallet <span class="badge-instant">Instant</span></div>
                    </a>
                </li>

                <li>
                    <a href="print_history">
                        <div class="parent-icon"><i class="fas fa-history text-info"></i></div>
                        <div class="menu-title">Print History</div>
                    </a>
                </li>

                <li>
                    <a href="news_updates">
                        <div class="parent-icon">
                            <i class="fas fa-newspaper text-warning <?php echo $unreadNews > 0 ? 'news-pulse' : ''; ?>"></i>
                        </div>
                        <div class="menu-title">
                            Today News
                            <?php if($unreadNews > 0): ?>
                                <span class="badge-count"><?php echo $unreadNews; ?></span>
                            <?php endif; ?>
                        </div>
                    </a>
                </li>

                <li class="menu-label">📱 All Services</li>

                <li><a href="Uid_Flx-Services"><div class="parent-icon"><img src="../images/aadhaar_icon.jpg" width="28" style="border-radius:3px;"></div><div class="menu-title">Aadhaar Services</div></a></li>
                <li><a href="pan_card_service"><div class="parent-icon"><img src="../admin/uploads/Services/panservices.png" width="28" style="border-radius:3px;"></div><div class="menu-title">Pan Card Services</div></a></li>
                <li><a href="vahicle_card_service"><div class="parent-icon"><img src="../admin/uploads/Services/Yamaha-Bike-PNG.png" width="28" style="border-radius:3px;"></div><div class="menu-title">Vehicle Services</div></a></li>
                <li><a href="Voter_card_service"><div class="parent-icon"><img src="../admin/uploads/Services/voter.png" width="28" style="border-radius:3px;"></div><div class="menu-title">Voter Services</div></a></li>
                <li><a href="Ration_card_service"><div class="parent-icon"><img src="../admin/uploads/Services/ration1.png" width="28" style="border-radius:3px;"></div><div class="menu-title">Ration Services</div></a></li>
                <li><a href="ElectriBill_card_service"><div class="parent-icon"><img src="../admin/uploads/Services/electricBill.png" width="28" style="border-radius:3px;"></div><div class="menu-title">Electric Bill</div></a></li>
                <li><a href="FarmerStackService"><div class="parent-icon"><img src="../admin/uploads/Services/farmerLogo0.png" width="28" style="border-radius:3px;"></div><div class="menu-title">Farmer Services</div></a></li>
                <li><a href="Passbook_card_service"><div class="parent-icon"><img src="../admin/uploads/Services/1771198.png" width="28" style="border-radius:3px;"></div><div class="menu-title">Passbook Services</div></a></li>
                <li><a href="Other_card_service"><div class="parent-icon"><img src="../admin/uploads/Services/dlpng.png" width="28" style="border-radius:3px;"></div><div class="menu-title">Other Services</div></a></li>

                <?php if (!empty($activeManualServices)): ?>
                    <li class="menu-label">⚡ Premium Services</li>
                    <?php 
                    $serviceIcons = [
                        'll_apply_fee' => ['icon' => 'fa-car-side', 'color' => '#e74c3c'],
                        'mobile_lookup_fee' => ['icon' => 'fa-mobile-alt', 'color' => '#3498db'],
                        'aadhaar_lookup_fee' => ['icon' => 'fa-fingerprint', 'color' => '#9b59b6'],
                        'voter_direct_pdf_fee' => ['icon' => 'fa-vote-yea', 'color' => '#e67e22'],
                        'voter_mobile_link_fee' => ['icon' => 'fa-link', 'color' => '#1abc9c'],
                        'puc_bike_fee' => ['icon' => 'fa-certificate', 'color' => '#16a085'],
                        'puc_car_fee' => ['icon' => 'fa-certificate', 'color' => '#16a085'],
                        'dl_to_mobile_fee' => ['icon' => 'fa-id-card', 'color' => '#2980b9'],
                        'pan_aadhaar_otp_fee' => ['icon' => 'fa-file-invoice', 'color' => '#d35400'],
                        'tec_exam_fee' => ['icon' => 'fa-graduation-cap', 'color' => '#27ae60'],
                    ];
                    
                    foreach($activeManualServices as $svc): 
                        $counts = '';
                        $tableName = '';
                        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;
                        }
                        if(!empty($tableName)) {
                            $pending = mysqli_num_rows(mysqli_query($ahk_conn, "SELECT id FROM $tableName WHERE status='Pending'"));
                            if($pending > 0) $counts = "<span class='badge-count'>$pending</span>";
                        }
                        
                        $iconData = $serviceIcons[$svc['service_key']] ?? ['icon' => 'fa-bolt', 'color' => '#f39c12'];
                    ?>
                    <li>
                        <a href="<?php echo $svc['sidebar_link']; ?>">
                            <div class="parent-icon">
                                <i class="fas <?php echo $iconData['icon']; ?>" style="color:<?php echo $iconData['color']; ?>;"></i>
                            </div>
                            <div class="menu-title"><?php echo $svc['display_name']; ?><?php echo $counts; ?></div>
                        </a>
                    </li>
                    <?php endforeach; ?>
                <?php endif; ?>

                <li class="menu-label">📊 Reports & Help</li>
                <li><a href="wallet_history"><div class="parent-icon"><i class="fas fa-history text-info"></i></div><div class="menu-title">Wallet Record</div></a></li>
                <li><a href="complaint_request"><div class="parent-icon"><i class="fas fa-exclamation-circle text-warning"></i></div><div class="menu-title">Complaint Rise</div></a></li>
                <li><a href="complaint_request_list"><div class="parent-icon"><i class="fas fa-headset text-danger"></i></div><div class="menu-title">Complaint List</div></a></li>
                <li><a href="pricing_list"><div class="parent-icon"><i class="fas fa-rupee-sign text-success"></i></div><div class="menu-title">Pricing</div></a></li>

                <?php if (checkAdmin($udata['type']) == true) { ?>
                <li class="menu-label">⚙️ Admin Panel</li>
                
                <li>
                    <a href="javascript:;" class="has-arrow">
                        <div class="parent-icon"><i class="fas fa-cogs text-primary"></i></div>
                        <div class="menu-title">Service Management</div>
                    </a>
                    <ul>
                        <li><a href="service_management"><i class="bx bx-right-arrow-alt"></i>Manage Services</a></li>
                        <?php foreach($activeManualServices as $svc): 
                            $adminLink = str_replace('.php', '_admin.php', $svc['sidebar_link']);
                        ?>
                            <li><a href="<?php echo $adminLink; ?>"><i class="bx bx-right-arrow-alt"></i><?php echo str_replace(' Request', '', $svc['display_name']); ?></a></li>
                        <?php endforeach; ?>
                    </ul>
                </li>

                <li><a href="news_admin"><div class="parent-icon"><i class="fas fa-newspaper text-warning"></i></div><div class="menu-title">Manage News</div></a></li>
                <li><a href="messages_admin"><div class="parent-icon"><i class="fas fa-envelope text-info"></i></div><div class="menu-title">Messages <?php if($unreadMessages > 0): ?><span class="badge-count"><?php echo $unreadMessages; ?></span><?php endif; ?></div></a></li>
                <li><a href="complaint_request_list_admin"><div class="parent-icon"><i class="fas fa-headset text-info"></i></div><div class="menu-title">Complaint Admin</div></a></li>
                
                <li>
                    <a href="javascript:;" class="has-arrow">
                        <div class="parent-icon"><i class="fas fa-cog text-secondary"></i></div>
                        <div class="menu-title">Settings</div>
                    </a>
                    <ul>
                        <li><a href="pricing"><i class="bx bx-right-arrow-alt"></i>Pricing</a></li>
                        <li><a href="LogoUpdate"><i class="bx bx-right-arrow-alt"></i>Logo Update</a></li>
                        <li><a href="settings"><i class="bx bx-right-arrow-alt"></i>Website Details</a></li>
                    </ul>
                </li>
                <?php } ?>

                <li><a href="referral"><div class="parent-icon"><i class="fas fa-gift text-warning"></i></div><div class="menu-title">Refer & Earn</div></a></li>
                <li><a href="../includes/logout.php"><div class="parent-icon"><i class="fas fa-sign-out-alt text-danger"></i></div><div class="menu-title">Logout</div></a></li>
            </ul>
        </div>

        <header>
            <div class="topbar d-flex align-items-center">
                <nav class="navbar navbar-expand">
                    <div class="mobile-toggle-menu"><i class='bx bx-menu'></i></div>
                    
                    <?php
                    if (isset($_GET['gettoAdmin']) && $_GET['session'] == 'true') {
                        loginAsAdmin();
                    }

                    if (isset($_SESSION['adminasuser']) == true && $_SESSION['adminusername'] != NULL) {
                    ?>
                        <div class="search-bar flex-grow-1">
                            <div class="position-relative search-bar-box">
                                <a href="?gettoAdmin=1&session=true" class="btn btn-success btn-sm">← Back to Admin</a>
                            </div>
                        </div>
                    <?php } else { ?>
                        <div class="search-bar flex-grow-1">
                            <div class="position-relative search-bar-box">
                                <input type="text" class="form-control search-control" placeholder="Temporary Notepad...">
                                <span class="position-absolute top-50 search-show translate-middle-y"><i class='bx bx-notepad'></i></span>
                                <span class="position-absolute top-50 search-close translate-middle-y"><i class='bx bx-x'></i></span>
                            </div>
                        </div>
                    <?php } ?>
                    
                    <div style="margin-right:12px;">
                        <style>
                            #time {
                                color: #000;
                                font-size: 13px;
                                font-weight: 500;
                                background: #f1f1f1;
                                padding: 3px 8px;
                                border-radius: 4px;
                                box-shadow: 0 1px 2px rgba(0,0,0,0.1);
                            }
                            @media (max-width: 768px) { #time { display: none; } }
                        </style>
                        <span id="time"></span>
                        <script>
                            function refreshTime() {
                                let now = new Date();
                                let d = String(now.getDate()).padStart(2,'0');
                                let m = String(now.getMonth()+1).padStart(2,'0');
                                let y = now.getFullYear();
                                let h = now.getHours();
                                let min = String(now.getMinutes()).padStart(2,'0');
                                let s = String(now.getSeconds()).padStart(2,'0');
                                let ap = h>=12?'PM':'AM';
                                h = h%12||12;
                                document.getElementById("time").innerHTML = `${d}-${m}-${y} - ${h}:${min}:${s} ${ap}`;
                            }
                            refreshTime();
                            setInterval(refreshTime,1000);
                        </script>
                    </div>
                    
                    <a href="wallet" class="btn btn-dark btn-sm d-flex align-items-center" style="padding:5px 10px;border-radius:6px;">
                        <i class="fas fa-wallet" style="margin-right:5px;"></i>
                        <span style="font-weight:600;">₹<?= round($udata['balance'], 2) ?></span>
                    </a>

                    <div class="top-menu ms-auto">
                        <ul class="navbar-nav">
                            <li class="nav-item dropdown">
                                <a class="nav-link dropdown-toggle dropdown-toggle-nocaret position-relative" href="#" data-bs-toggle="dropdown">
                                    <?php if($unreadMessages > 0): ?>
                                        <span class="alert-count"><?php echo $unreadMessages; ?></span>
                                    <?php endif; ?>
                                    <i class='bx bx-envelope'></i>
                                </a>
                                <div class="dropdown-menu dropdown-menu-end">
                                    <a href="<?php echo checkAdmin($udata['type']) ? 'messages_admin' : 'user_messages'; ?>">
                                        <div class="msg-header">
                                            <p class="msg-header-title">Messages</p>
                                        </div>
                                    </a>
                                </div>
                            </li>
                        </ul>
                    </div>
                    
                    <div class="user-box dropdown">
                        <a class="d-flex align-items-center nav-link dropdown-toggle dropdown-toggle-nocaret" href="#" data-bs-toggle="dropdown">
                            <img src="../admin/uploads/Profile-Male-PNG.png" class="user-img" alt="user">
                            <div class="user-info ps-3">
                                <p class="user-name mb-0"><?php echo $udata['name']; ?></p>
                            </div>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="profile"><i class="bx bx-user"></i> Profile</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="../includes/logout.php"><i class='bx bx-log-out-circle'></i> Logout</a></li>
                        </ul>
                    </div>
                </nav>
            </div>
        </header>
        
        <div id="page-loader" style="position:fixed;top:0;left:0;width:100vw;height:100vh;background:rgba(0,0,0,0.6);z-index:99999;display:none;justify-content:center;align-items:center;">
            <div style="border:5px solid #f3f3f3;border-top:5px solid #3498db;border-radius:50%;width:60px;height:60px;animation:spin 1s linear infinite;"></div>
        </div>
        <style>@keyframes spin{to{transform:rotate(360deg)}}</style>
        <script>
            window.addEventListener("load",()=>document.getElementById("page-loader").style.display="none");
            document.querySelectorAll("form").forEach(f=>f.addEventListener("submit",()=>document.getElementById("page-loader").style.display="flex"));
        </script>