<?php
session_start();
$key = md5(date("Y-m-d").":".$_SERVER['REMOTE_ADDR']);
if (isset($_SESSION['aW1iZXN0cmEuY29tLm15']) <> $key) {
    header("location:".$_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME']); // cara baru !
} else {
    require "conn.php";
    include "_header.php";
    include "_navtop.php";
    include "_navside.php";
    include "_functions.php";

    $mwallet_transaction    = MsumWall("keluar", "mwallet");
    $mwallet                = MsumWall("masuk", "mwallet") - sumWall("keluar", "mwallet");
    $cwallet                = sumWall("masuk", "cwallet") - sumWall("keluar", "cwallet");
    $cwallet_carwash        = sumWall("masuk", "cwallet_carwash") - sumWall("keluar", "cwallet_carwash");
    $cwallet_travel         = sumWall("masuk", "cwallet_travel") - sumWall("keluar", "cwallet_travel");                 // wax & polish
    $cwallet_cash           = sumWall("masuk", "cwallet_cash") - sumWall("keluar", "cwallet_cash");                     // repair
    $cwallet_accessories    = sumWall("masuk", "cwallet_accessories") - sumWall("keluar", "cwallet_accessories");
    $cwallet_insurance      = sumWall("masuk", "cwallet_insurance") - sumWall("keluar", "cwallet_insurance");
    $sms_balance            = chkSMS();
    $limit = 100;
    
$members        = getStatCount("members");
$package        = getStatCount("package");
$product        = getStatCount("product");
$order          = getStatCount("order");
$sales_total    = getStatCount("sales");      // sum of grand_total from sales table
$bonus_wallet   = getStatCount("bonus");      // sum of masuk from cwallet
$withdraw_total = getStatCount("withdrawal"); // sum or count from withdrawal table
$tax_total      = getStatCount("tax");        // sum of tax
$profit_total   = getStatCount("profit");     // sum of profit
$sms_balance    = getStatCount("sms");        // sms balance


    if ($cwallet >= $limit) {
        $link = "request_withdraw.php";
    } else {
        $link = "#";
    }

    $result = mysqli_query($con, "SELECT SUM(amaun) FROM withdraw WHERE userid='".$_SESSION['aidi']."'");
    $withdraw = mysqli_fetch_array($result);

                                if (isset($_POST['btn_tx_trn_insurance_cash'])) {
                                    
		                            date_default_timezone_set("Asia/Kuala_Lumpur");
		                            $tarikh                 = date("Y-m-d H:i:s");                                    
                                    $uid                    = $_SESSION['aidi'];
                                    $unama                  = strtoupper($_SESSION['namapenuh']);
                                    $tx_insurancecash       = $_POST['tx_insurance_cash'];
                                    $surcharge_data         = number_format((4 * $tx_insurancecash)/100,2); 
                                    $tx_data                = number_format($tx_insurancecash - $surcharge_data,2); 
                                    $tx_keterangan          = "Transfer Insurance Bonus to CASH Bonus *Surcharge: RM".$surcharge_data; 
                                    $cash_keterangan        = "Received RM".$surcharge_data." surcharge Insurance Bonus from ".$_SESSION['namapenuh'];  
                                    // duit keluar insurance bonus - members
                                    mysqli_query($con, "INSERT INTO cwallet_insurance (tarikh, keterangan, rujukan, keluar, userid)
                                    VALUES ('".$tarikh."', '".$tx_keterangan."', '".$unama."', '".$tx_insurancecash."', '".$uid."')");
                                    // duit masuk cash bonus - members
                                    mysqli_query($con, "INSERT INTO cwallet (tarikh, keterangan, rujukan, masuk, userid)
                                    VALUES ('".$tarikh."', '".$tx_keterangan."', '".$unama."', ".$tx_data.", ".$uid.")");
                                    // duit masuk cash bonus - admin
                                    mysqli_query($con, "INSERT INTO cwallet (tarikh, keterangan, rujukan, masuk, userid)
                                    VALUES ('".$tarikh."', '".$cash_keterangan."', '".$unama."', ".$surcharge_data.", '1')");
                                  
                                    
                          }


?>
        <div id="page-wrapper" >
            <div id="page-inner">
                <div class="row">
                    <div class="col-md-12">
                     <h2>Dashboard</h2>
                        <h5>Welcome <?= $_SESSION['namapenuh'] ?> , Love to see you back. </h5>
                    </div>
                </div>
                 <!-- /. ROW  -->

                 <!-- /. ROW  -->
                <hr />
                
<?php
//if ($_SESSION['username'] <> "admin")  {

    if (($_SESSION['role']) <> "merchant") {
            if ($_SESSION['role'] == "user")    {          
?>

                <div class="row">
                    <div class="col-md-12 col-sm-12 col-xs-12">
                        <h4>Available Balance</h4>
                    </div>
                    <div class="col-md-4 col-sm-4 col-xs-12">
                        <div class="panel panel-back noti-box" style="box-shadow:0 4px 8px rgba(0,0,0,0.1); border-radius:8px;" >
                            <span class="icon-box bg-primary set-icon" >
                                <i class="fa fa-usd" ></i>
                            </span>
                            <div class="text-box small" >
                                <p class="main-text"><span class="small" style="font-size:15px; padding-right:10px;">RM </span><?= number_format($cwallet,2) ?></p>
                                <p class="text-muted">Total Bonus</p>
                            </div>
                        </div>
                    </div>


                    <div class="col-md-4 col-sm-4 col-xs-12">
                        <div class="panel panel-back noti-box" style="box-shadow:0 4px 8px rgba(0,0,0,0.1); border-radius:8px;">
                            <span class="icon-box bg-primary set-icon">
                                <i class="fa fa-solid fa-hourglass-start"></i>
                            </span>
                        <div class="text-box small" >
                            <p class="main-text"><span class="small" style="font-size:15px; padding-right:10px;">RM </span><?= number_format(0,2) ?></p>
                            <p class="text-muted">Pending Bonus</p>
                        </div>
                        </div>
                    </div>
<?php
                    date_default_timezone_set("Asia/Kuala_Lumpur");
                    
                    // check if user has downline
                    $dwnln  = mysqli_num_rows(mysqli_query($con, "SELECT id FROM ahli WHERE penaja = '".$_SESSION['aidi']."'"));
                    $upkges = mysqli_num_rows(mysqli_query($con, "SELECT pakej FROM ahli WHERE id = '".$_SESSION['aidi']."'"));
                    
                    if (($upkges != "platinum") && (!empty($upkges)) )  {
                        if ($dwnln == 0) {
                            $sql = "SELECT DATE_ADD(tarikh, INTERVAL 3 MONTH) AS expired, tarikh FROM `ahli` WHERE id = ".$_SESSION['aidi'];
                            $row = mysqli_fetch_array(mysqli_query($con, $sql));
                            $expired = $row['expired'];
                            $start = $row['tarikh'];
                            $expiredTimestamp = strtotime($expired);
                            $startTimestamp = strtotime($start);
                            $totalDuration = $expiredTimestamp - $startTimestamp; // seconds
                        ?>
                        <div class="col-md-4 col-sm-4 col-xs-12">
                            <div class="panel panel-back noti-box" style="box-shadow:0 4px 8px rgba(0,0,0,0.1); border-radius:8px;">
                                <span class="icon-box bg-primary set-icon">
                                    <i class="fa-solid fa-person-arrow-up-from-line"></i>
                                </span>
                                <div class="text-box small">
                                    <p class="main-text text-center">
                                        <span class="small" id="countdown" style="font-size:25px; color:red; padding-right:10px;">Calculating...</span>
                                    </p>
                                    <p class="text-muted text-center">
                                        Upgrade Expired : <strong style="color:red;"><?= date("d-m-Y", strtotime($expired)) ?></strong>
                                    </p>
                                    
                                </div>
                            </div>
                        </div>
                        
                        <script>
                        const countdownElement = document.getElementById('countdown');
                        const expireTime = <?= $expiredTimestamp ?> * 1000; // milliseconds
                        const startTime = <?= $startTimestamp ?> * 1000; // milliseconds
                        const totalDuration = <?= $totalDuration ?> * 1000;
                        
                        function updateCountdown() {
                            const now = new Date().getTime();
                            const distance = expireTime - now;
                        
                            if(distance <= 0){
                                countdownElement.innerHTML = "Expired";
                                progressBar.style.width = "100%";
                                clearInterval(interval);
                                return;
                            }
                        
                            const days = Math.floor(distance / (1000 * 60 * 60 * 24));
                            const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000*60*60));
                            const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000*60));
                            const seconds = Math.floor((distance % (1000 * 60)) / 1000);
                        
                            countdownElement.innerHTML = `${days}<span style="color:black; font-size:15px;">d</span> ${hours}<span style="color:black; font-size:15px;">h</span> ${minutes}<span style="color:black; font-size:15px;">m</span> ${seconds}<span style="color:black; font-size:15px;">s</span>`;
                        
                            // progress bar calculation
                            const elapsed = now - startTime;
                            const percent = (elapsed / totalDuration) * 100;
                        }
                        
                        // update every second
                        updateCountdown();
                        const interval = setInterval(updateCountdown, 1000);
                        </script>
                        
                        
                        
                        <?php } 
                    }                     
            }
                        if ($_SESSION['role'] == "admin")  {               ?>
                        
                        
                        <style>
                            .stat-card {
                                background:#fff;
                                border-radius:8px;
                                padding:18px 22px;
                                border:1px solid #e7e7e7;
                                box-shadow:0 1px 3px rgba(0,0,0,0.08);
                                transition:.25s;
                                text-align:center;
                                cursor:pointer;
                            }
                            .stat-card:hover {
                                transform:translateY(-3px);
                                box-shadow:0 6px 12px rgba(0,0,0,0.15);
                            }
                            .stat-value {
                                font-size:28px;
                                font-weight:700;
                                color:#333;
                                margin-bottom:3px;
                            }
                            .stat-label {
                                font-size:14px;
                                color:#777;
                            }
                        </style>
                        
<!-- Dashboard Statistics Cards -->
        <div class="row">
            <?php
            // Dashboard statistics items
            $stats = [
                "members"       => ["icon" => "fa-users", "label" => "Members", "bg" => "bg-primary"],
                "package"       => ["icon" => "fa-box-open", "label" => "Packages", "bg" => "bg-primary"],
                "product"       => ["icon" => "fa-cube", "label" => "Products", "bg" => "bg-primary"],
                "order"         => ["icon" => "fa-receipt", "label" => "Orders", "bg" => "bg-primary"],
                "payment"       => ["icon" => "fa-credit-card", "label" => "Payments", "bg" => "bg-primary"],
                "sales"         => ["icon" => "fa-money-bill-wave", "label" => "Sales", "bg" => "bg-primary"],
                "bonus"         => ["icon" => "fa-gift", "label" => "Bonus", "bg" => "bg-primary"],
                "tax"           => ["icon" => "fa-percent", "label" => "Tax", "bg" => "bg-primary"],
                "profit"        => ["icon" => "fa-chart-line", "label" => "Profit", "bg" => "bg-primary"],
                "withdrawal"    => ["icon" => "fa-wallet", "label" => "Withdrawal", "bg" => "bg-primary"],
                "packaging"     => ["icon" => "fa-box", "label" => "Packaging", "bg" => "bg-primary"],
                "shipping"      => ["icon" => "fa-truck", "label" => "Shipping", "bg" => "bg-primary"],
                "sms"           => ["icon" => "fa-sms", "label" => "SMS", "bg" => "bg-primary"]
            ];

            foreach($stats as $key => $info) {
                $value = getStatCount($key);
            ?>
                <div class="col-lg-3 col-md-6 col-sm-12 mb-4">
                    <div class="panel panel-back noti-box" style="box-shadow:0 4px 8px rgba(0,0,0,0.1); border-radius:8px;">
                        <span class="icon-box <?= $info['bg'] ?> set-icon">
                            <i class="fa <?= $info['icon'] ?>"></i>
                        </span>
                        <div class="text-box small">
                            <p class="main-text">
                                <?php if(in_array($key, ['sales','bonus','tax','profit','sms'])): ?>
                                    <span style="font-size:10px;">RM</span> <?= number_format($value,2) ?>
                                <?php else: ?>
                                    <?= $value ?>
                                <?php endif; ?>
                            </p>
                            <p class="text-muted"><?= $info['label'] ?></p>
                        </div>
                    </div>
                </div>
            <?php } ?>
        </div>
        <!-- /.row -->
                        
                        
                        
                            <div class="col-md-4 col-sm-4 col-xs-12">
                                <div class="panel panel-back noti-box" style="box-shadow:0 4px 8px rgba(0,0,0,0.1); border-radius:8px;">
                                    <span class="icon-box bg-primary set-icon">
                                        <i class="fa-solid fa-comment-dollar"></i>
                                    </span>
                                    <div class="text-box small">
                                        <p class="main-text">
                                           <span class="small" style="font-size:15px; padding-right:10px;">RM </span>
                                           <?= number_format($sms_balance, 2) ?>
                                        </p>
                                        <p class="text-muted">SMS Gateway</p>
                                    </div>
                                </div>
                            </div>
<?php                   }               ?>
           </div>
                 <!-- /. ROW  -->
                <hr />
<? 
            
    }   else    {
?>
                <div class="container">
<?php   if ($_SESSION['role'] == "user")    {   ?>                  
                    <div class="row">
                        <div class="col-md-4 col-sm-12 col-xs-12 bg-warningk">
                            <div class="panel panel-back noti-box" >
                                <span class="icon-box bg-primary set-icon" >
                                    <i class="fa fa-usd" ></i>
                                </span>
                                <div class="text-box small" >
                                    <p class="main-text"><span class="small" style="font-size:15px; padding-right:10px;">RM </span><?= number_format($mwallet,2) ?></p>
                                    <p class="text-muted">Available Balance</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4 col-sm-12 col-xs-12 bg-warningk">
                            <div class="panel panel-back noti-box" >
                                <span class="icon-box bg-primary set-icon" >
                                    <i class="fa fa-money-bill-transfer" ></i>
                                </span>
                                <div class="text-box small" >
                                    <p class="main-text"><span class="small" style="font-size:15px; padding-right:10px;">RM </span><?= number_format($mwallet_transaction ?? 0, 2) ?></p>
                                    <p class="text-muted">Total Withdrawal</p>
                                </div>
                            </div>
                        </div>
                    </div>
<?php   }   ?>
                </div>
<?php
    }

?>
    </div>
             <!-- /. PAGE INNER  -->
            </div>
         <!-- /. PAGE WRAPPER  -->
        </div>
<?php
    include "_footer.php";
}
?>