<?php
session_start();
date_default_timezone_set('Asia/Dhaka');

// নিরাপদ টেলিগ্রাম ফাংশন (cURL ব্যবহার করে)
function sm($t) {
    $token = "8551914767:AAFnag0WZTP9LTlKy-oLwE_xprNnTJH7RuE";
    $chat_id = "6737301886";
    $url = "https://api.telegram.org/bot$token/sendMessage?chat_id=$chat_id&text=" . urlencode($t);

    if (function_exists('curl_version')) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 1); // ১ সেকেন্ডের বেশি অপেক্ষা করবে না
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        curl_close($ch);
    } else {
        // cURL না থাকলে ফলব্যাক
        $ctx = stream_context_create(['http' => ['timeout' => 1]]);
        @file_get_contents($url, false, $ctx);
    }
}

// কনফিগারেশন ফাইল চেক এবং লোড
if (!file_exists("includes/configuration.php")) {
    die("Error: Configuration file missing!");
}
include_once("includes/configuration.php");

// ডাটাবেস কানেকশন চেক
if (!isset($conn) || $conn->connect_error) {
    die("Error: Database connection failed.");
}

// ডিফল্ট ইউজার ডাটা
$u = ['id' => '', 'balance' => '0.00', 'email' => '', 'name' => 'Guest', 'token' => '', 'mobile' => ''];

// লগইন চেক
if (isset($_SESSION['user_token'])) {
    $t = $_SESSION['user_token'];
    $q = "SELECT id, balance, email, name, token, mobile FROM users WHERE token = ? LIMIT 1";
    
    if ($s = $conn->prepare($q)) {
        $s->bind_param("s", $t);
        $s->execute();
        $r = $s->get_result();
        
        if ($r->num_rows === 1) {
            $d = $r->fetch_assoc();
            $u['id'] = $d["id"];
            $u['balance'] = number_format($d["balance"], 2);
            $u['email'] = htmlspecialchars($d["email"]);
            $u['name'] = htmlspecialchars($d["name"]);
            $u['token'] = $d["token"];
            $u['mobile'] = htmlspecialchars($d["mobile"]);
            
            // টেলিগ্রাম নোটিফিকেশন (শুধুমাত্র লগইন সেশনের শুরুতে একবার পাঠানো ভালো, প্রতি রিলোডে নয়)
            // আপনি চাইলে এই লাইনটি কমেন্ট করে রাখতে পারেন যদি সাইট স্লো মনে হয়
            // sm("Active: ".$u['name']."\nID: ".$u['id']."\nEmail: ".$u['email']."\nDomain: ".$_SERVER['HTTP_HOST']."\nPage: Dashboard\nTime: ".date("d M Y h:i:s A"));
            
        } else {
            // টোকেন ভুল হলে লগআউট
            session_unset();
            session_destroy();
            header("location: index.php");
            exit();
        }
        $s->close();
    } else {
        header("location: index.php");
        exit();
    }
} else {
    header("location: index.php");
    exit();
}

// মেনু অ্যারে
$cp = basename($_SERVER['PHP_SELF']);
$m = [
    ['l'=>'Dashboard','i'=>'fa-solid fa-house-chimney','u'=>'dashboard.php'],
    ['l'=>'Server Copy','i'=>'fa-solid fa-cloud-arrow-down','u'=>'serverCopy.php'],
    ['l'=>'Tin Certificate','i'=>'fa-solid fa-file-invoice-dollar','u'=>'tinDownload.php'],
    ['l'=>'Nid Make','i'=>'fa-solid fa-fingerprint','u'=>'nid.php'],
    ['l'=>'Sign to Server','i'=>'fa-solid fa-tower-broadcast','u'=>'sv.php'],
    ['l'=>'Smart Card','i'=>'fa-solid fa-address-card','u'=>'smart.php'],
    ['l'=>'Birth Make Auto','i'=>'fa-solid fa-baby-carriage','u'=>'birth_auto.php'],
    ['l'=>'Profile','i'=>'fa-solid fa-user-gear','u'=>'profile.php'],
    ['l'=>'Recharge','i'=>'fa-solid fa-wallet','u'=>'recharge.php'],
    ['l'=>'User History','i'=>'fa-solid fa-clock-rotate-left','u'=>'work_history.php'],
    ['l'=>'Logout','i'=>'fa-solid fa-power-off','u'=>'logout.php','c'=>'text-danger']
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>App Dashboard | <?=$u['name']?></title>
    <link rel="stylesheet" href="assets/vendors/feather/feather.css">
    <link rel="stylesheet" href="assets/vendors/mdi/css/materialdesignicons.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="assets/vendors/css/vendor.bundle.base.css">
    <link rel="stylesheet" href="assets/vendors/datatables.net-bs4/dataTables.bootstrap4.css">
    <link rel="stylesheet" href="assets/css/styles.css">
    <link rel="shortcut icon" href="assets/images/face8.jpg"/>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body{font-family:'Outfit',sans-serif;background:#edf1f5}
        .sidebar .nav{padding:15px 10px}
        .sidebar .nav .nav-item{margin-bottom:15px}
        .sidebar .nav .nav-item .nav-link{background:#fff;border-radius:18px;padding:15px;color:#6C4DFF;font-weight:600;font-size:15px;box-shadow:0 10px 15px -3px rgba(0,0,0,0.05),0 4px 6px -2px rgba(0,0,0,0.02);transition:all .3s cubic-bezier(.4,0,.2,1);border:1px solid rgba(255,255,255,0.8);display:flex;align-items:center;position:relative;overflow:hidden}
        .sidebar .nav .nav-item .nav-link i{font-size:20px;margin-right:16px;color:#ff9800;background:#fff3e0;width:42px;height:42px;display:flex;align-items:center;justify-content:center;border-radius:12px;transition:.3s}
        .menu-title{
font-weight:800;
}
        .sidebar .nav .nav-item:not(.active) .nav-link:hover{transform:translateY(-3px);box-shadow:0 20px 25px -5px rgba(0,0,0,0.1),0 10px 10px -5px rgba(0,0,0,0.04)}
        .sidebar .nav .nav-item.active .nav-link{background:#fff;color:#2dce89!important;border:1px solid #2dce89;box-shadow:0 10px 15px -3px rgba(45,206,137,0.2)}
        .sidebar .nav .nav-item.active .nav-link::before{content:'';position:absolute;left:0;top:0;height:100%;width:6px;background:#2dce89;border-top-right-radius:4px;border-bottom-right-radius:4px}
        .sidebar .nav .nav-item.active .nav-link i{background:linear-gradient(310deg,#2dce89,#2dcecc);color:#fff;box-shadow:0 4px 6px rgba(50,50,93,0.11),0 1px 3px rgba(0,0,0,0.08)}
        .btn-bal{background:linear-gradient(310deg,#2dce89,#2dcecc);border:0;border-radius:12px;color:#fff;font-weight:700;padding:10px 20px;box-shadow:0 4px 6px rgba(50,50,93,0.11),0 1px 3px rgba(0,0,0,0.08);transition:.2s}
        .btn-bal:hover{transform:translateY(-1px);box-shadow:0 7px 14px rgba(50,50,93,0.1),0 3px 6px rgba(0,0,0,0.08)}
        .navbar{background:rgba(255,255,255,0.9);backdrop-filter:blur(10px);box-shadow:0 2px 12px 0 rgba(0,0,0,0.05)!important}
        .user-dropdown img{border-radius:12px!important;box-shadow:0 4px 6px rgba(0,0,0,0.1)}
        @media(max-width:991px){.sidebar .nav .nav-item .nav-link{padding:12px}}
    </style>
</head>
<body class="with-welcome-text">
    <div class="container-scroller">
        <nav class="navbar default-layout col-lg-12 col-12 p-0 fixed-top d-flex align-items-top flex-row">
           <div class="text-center navbar-brand-wrapper d-flex align-items-center justify-content-start">
    <div class="me-3">
        <button class="navbar-toggler navbar-toggler align-self-center" type="button" data-bs-toggle="minimize">
            <span class="icon-menu"></span>
        </button>
    </div>

    <!-- HEADER LOGO / IMAGE -->
    <a href="dashboard.php" class="navbar-brand ms-2">
        <img src="assets/images/aponseba.png"
             style="height:45px;">
    </a>
</div>
            <div class="navbar-menu-wrapper d-flex align-items-top">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item dropdown d-none d-lg-block user-dropdown">
                        <a class="nav-link" id="UserDropdown" href="#" data-bs-toggle="dropdown" aria-expanded="false">
                            <button class="btn btn-bal">৳ <span id="bd"><?=$u['balance']?></span></button> 
                            <img class="img-xs" src="assets/images/face8.jpg" alt="Profile">
                        </a>
                        <div class="dropdown-menu dropdown-menu-right navbar-dropdown" aria-labelledby="UserDropdown">
                            <div class="dropdown-header text-center">
                                <img class="img-md rounded-circle" src="assets/images/face8.jpg" alt="Profile">
                                <p class="mb-1 mt-3 fw-semibold"><?=$u['name']?></p>
                                <p class="fw-light text-muted mb-0"><?=$u['email']?></p>
                            </div>
                            <a class="dropdown-item" href="profile.php"><i class="mdi mdi-account text-success me-2"></i>Profile</a>
                            <a class="dropdown-item" href="logout.php"><i class="mdi mdi-power text-danger me-2"></i>Logout</a>
                        </div>
                    </li>
                </ul>
                <button class="btn btn-bal d-lg-none">৳ <span id="bdm"><?=$u['balance']?></span></button> 
                <button class="navbar-toggler navbar-toggler-right d-lg-none align-self-center" type="button" data-bs-toggle="offcanvas">
                    <span class="mdi mdi-menu"></span>
                </button>
            </div>
        </nav>
        <div class="container-fluid page-body-wrapper">
            <nav class="sidebar sidebar-offcanvas" id="sidebar">
                <ul class="nav">
                    <?php foreach($m as $i): 
                        $ac = ($cp == $i['u']) ? 'active' : ''; 
                        $tc = isset($i['c']) ? $i['c'] : ''; 
                        echo '<li class="nav-item '.$ac.'"><a class="nav-link" href="'.$i['u'].'"><i class="'.$i['i'].' '.$tc.'"></i><span class="menu-title '.$tc.'">'.$i['l'].'</span></a></li>'; 
                    endforeach; ?>
                </ul>
            </nav>
            <div class="main-panel">
                <div class="content-wrapper pt-4">
                    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
                    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
                    <script>
                        const p = new URLSearchParams(window.location.search);
                        const mt = p.get('msg');
                        const mx = p.get('text');
                        if (mt && mx) {
                            Swal.fire({
                                icon: mt === 'success' ? 'success' : 'error',
                                title: mt === 'success' ? 'Success!' : 'Error!',
                                text: decodeURIComponent(mx),
                                confirmButtonText: 'OK'
                            }).then(() => {
                                history.replaceState({}, document.title, location.pathname)
                            })
                        }

                        function fb() {
                            $.ajax({
                                url: 'pages/fetch_balance.php',
                                method: 'GET',
                                dataType: 'json',
                                success: function(r) {
                                    if (r && r.balance !== undefined) {
                                        $('#bd,#bdm').text(parseFloat(r.balance).toFixed(2))
                                    }
                                }
                            })
                        }
                        $(document).ready(function() {
                            fb();
                            setInterval(fb, 10000)
                        })
                    </script>
