<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/tngweb/header.php');
$versionFile = '../update/current_version.txt';
$currentVersion = file_exists($versionFile) ? trim(file_get_contents($versionFile)) : '1.0.0';

$updateInfoJson = fetchUpdateInfo($updateApiUrl);
$updateData = json_decode($updateInfoJson, true);
$nextUpdate = null;


if(isset($updateData['updates']) && is_array($updateData['updates'])){
    foreach($updateData['updates'] as $update){
        if(version_compare($update['version'], $currentVersion, '>')){
            $nextUpdate = $update;
            break; 
        }
    }
}

$updateAvailable = $nextUpdate !== null;





$buttonText = "💰 Check API Balance";

if (isset($_POST['check_balance'])) {
    // Database se API Key fetch karna (JkL_get function ka use karke)
    $apikey = JkL_get('TheNextGenAPI', 'tng_apikey');

    if (!empty($apikey)) {
        $responseApi = getApiBalance($apikey);
        $response = json_decode($responseApi, true);

        // Naye JSON format: {"status":"success", "balance":"996317.80", ...}
        if (isset($response['status']) && $response['status'] == "success") {
            // Number format karke dikhayenge (₹9,96,317.80)
            $formattedBalance = number_format((float)$response['balance'], 2);
            $buttonText = "💵 Balance: ₹" . $formattedBalance;
        } else {
            // Agar API status success nahi hai
            $msg = $response['message'] ?? 'Invalid Response';
            $buttonText = "❌ " . $msg;
        }
    } else {
        $buttonText = "❌ API Key Missing";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?php echo XyZ_val('brand'); ?> | <?php echo XyZ_val('title'); ?></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
body { background:#f5f5f5; }
/* WhatsApp */
.whatsapp-float { position:fixed; bottom:20px; right:20px; width:55px; height:55px; background:#25D366; border-radius:50%; display:flex; align-items:center; justify-content:center; box-shadow:2px 2px 10px rgba(0,0,0,0.3);}
.whatsapp-float img { width:28px; height:28px; }
/* Cards */
.hand { cursor:pointer; margin-bottom:20px; transition:0.3s; }
.hand:hover { transform:translateY(-5px); box-shadow:0 8px 20px rgba(0,0,0,0.2);}
.card-icon img { max-width:80px; height:80px; margin-bottom:10px; border-radius:10px; object-fit:cover; }
.card-text { font-weight:bold; font-size:15px; color:#333; }
.card { border-radius:10px; background:#fff; }
/* Summary */
.summary-card { text-align:center; padding:20px; color:white; border-radius:12px; margin-bottom:20px; font-weight:500; }
.bg-wallet { background:#007bff; }
.bg-admin { background:#28a745; }
.bg-distributor { background:#ffc107; color:#000; }
.bg-users { background:#6f42c1; }
/* Banner */
.banner-container { background:#fff; padding:12px 20px; border-radius:10px; margin-bottom:15px; display:flex; justify-content:space-between; align-items:center; box-shadow:0 5px 15px rgba(0,0,0,0.05);}
</style>
</head>
<body>
<?php
if (
    XyZ_val('popup_active') == "on" &&
    $udata['type'] != 'admin' && 
    in_array($udata['type'], ['master','prime','distributor','retailer'])
) { ?> 

<style>
  .overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background: rgba(0,0,0,0.7);
    backdrop-filter: blur(6px);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
    animation: fadeInBg 0.5s ease;
  }

  .popup {
    background: rgba(20,20,20,0.9);
    color: #fff;
    padding: 28px 35px;
    border-radius: 18px;
    width: 420px;
    max-width: 90%;
    text-align: center;
    font-family: 'Segoe UI', sans-serif;
    box-shadow: 0 10px 30px rgba(0,0,0,0.5), 
                0 0 15px rgba(0,200,255,0.6);
    animation: slideUp 0.4s ease;
    position: relative;
  }

  .popup h3 {
    margin-bottom: 10px;
    font-size: 24px;
    color: #00eaff;
    text-shadow: 0 0 10px rgba(0,234,255,0.7);
  }

  .popup h6 {
    font-size: 16px;
    line-height: 1.5;
    color: #ddd;
    margin: 0;
  }

  .popup .close-btn {
    position: absolute;
    top: 12px;
    right: 12px;
    background: none;
    border: none;
    font-size: 20px;
    cursor: pointer;
    color: #fff;
    transition: all 0.2s ease;
  }

  .popup .close-btn:hover {
    color: #00eaff;
    transform: rotate(90deg);
  }

  @keyframes fadeInBg {
    from { opacity: 0; }
    to { opacity: 1; }
  }

  @keyframes slideUp {
    from { opacity: 0; transform: translateY(30px) scale(0.95); }
    to { opacity: 1; transform: translateY(0) scale(1); }
  }
</style>

<div class="overlay" id="popupOverlay">
  <div class="popup">
    <button class="close-btn" onclick="closePopup()">✖</button>
    <h3>📌 Alert!</h3>
    <h6><?php echo XyZ_val('popupalert') ?? ''; ?></h6>
  </div>
</div>

<script>
  function closePopup() {
    document.getElementById("popupOverlay").style.display = "none";
  }
</script>

<?php } ?>


<div class="page-wrapper">
<div class="page-content container mt-4">

  <!-- Welcome -->
  <div class="row mb-3"><div class="col-md-12"><h5 class="text-dark font-weight-bold">Hi,<?= $udata['name']?></h5></div></div>
<?php if($udata['id'] == "1" || $udata['type'] == "admin"){ ?>
  <div class="banner-container" style="padding:10px; background:#f5f5f5; border:1px solid #ddd; margin-bottom:15px;">
    <?php if($updateAvailable){ ?>
        <span>🚀 Update Available! (New Version <?= htmlspecialchars($nextUpdate['version']) ?>)</span>
        <button class="btn btn-warning btn-sm" onclick="showUpdatePopup()">Update Now</button>
        <div style="margin-top:5px; font-size:0.9em; color:#555;"><?= htmlspecialchars($nextUpdate['changelog']) ?></div>
    <?php } else { ?>
        <span>✅ Your system is up to date! (Version <?= htmlspecialchars($currentVersion) ?>)</span>
    <?php } ?>
  <form method="post" style="margin:0;">
        <button type="submit" name="check_balance" class="btn btn-light btn-sm"><?= $buttonText ?></button>
    </form>
  </div>
<?php } ?>
  <!-- Carousel -->
  <div class="col-md-12 mb-2">
       <div class="row">
    <div class="card p-1 text-danger">
      <div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
        <div class="carousel-inner">
          <div class="carousel-item active"><img class="d-block w-100" src="https://<?php echo $_SERVER['SERVER_NAME']; ?>/template/tngweb/assets/images/banner.webp" style="height:120px"></div>
          <div class="carousel-item"><img class="d-block w-100" src="https://<?php echo $_SERVER['SERVER_NAME']; ?>/template/tngweb/assets/images/banner2.webp" style="height:120px"></div>
          <div class="carousel-item"><img class="d-block w-100" src="https://<?php echo $_SERVER['SERVER_NAME']; ?>/template/tngweb/assets/images/banner3.webp" style="height:120px"></div>
          <div class="carousel-item"><img class="d-block w-100" src="https://<?php echo $_SERVER['SERVER_NAME']; ?>/template/tngweb/assets/images/mobile-recha.jpg" style="height:120px"></div>
          <div class="carousel-item"><img class="d-block w-100" src="https://<?php echo $_SERVER['SERVER_NAME']; ?>/template/tngweb/assets/images/nsdl_pan_banner.jpg" style="height:120px"></div>
          <div class="carousel-item"><img class="d-block w-100" src="https://<?php echo $_SERVER['SERVER_NAME']; ?>/template/tngweb/assets/images/tngdigital.jpg" style="height:120px"></div>
          <div class="carousel-item"><img class="d-block w-100" src="https://<?php echo $_SERVER['SERVER_NAME']; ?>/template/tngweb/assets/images/banner3.jpg" style="height:120px"></div>
          <div class="carousel-item"><img class="d-block w-100" src="https://<?php echo $_SERVER['SERVER_NAME']; ?>/template/tngweb/assets/images/nsdl_Paperless_Pan_Card_Apply.jpg" style="height:120px"></div>
        </div>
        <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
          <span class="carousel-control-prev-icon" aria-hidden="true"></span>
          <span class="sr-only">Previous</span>
        </a>
        <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
          <span class="carousel-control-next-icon" aria-hidden="true"></span>
          <span class="sr-only">Next</span>
        </a>
      </div>
    </div>
  </div>

  <!-- Services -->
  <div class="row">
  <?php
foreach($servicesIndex as $srv){ 
    if(!isset($srv['db']) || !isset($udata[$srv['db']]) || $udata[$srv['db']] !== 'on'){
        continue;
    }
?>
    <div class="col-lg-3 col-md-6 col-sm-6 hand">
      <a href="<?= $srv['link']?>" style="text-decoration:none;">
        <div class="card text-center p-3">
          <div class="card-icon"><img src="https://<?php echo $_SERVER['SERVER_NAME']; ?>/template/tngweb/assets/images/<?= $srv['img']?>" alt="<?= $srv['text']?>"></div>
          <p class="card-text"><?= $srv['text']?></p>
          <span class="badge badge-primary">View Service</span>
        </div>
      </a>
    </div>
<?php } ?>

  </div>

  <?php
$userid = $udata['phone'];
$userType = $udata['type']; 

function formatAmt($amt){
    return "₹" . number_format($amt, 2);
}

$today = date('Y-m-d');
$monthStart = date('Y-m-01');

// Initialize variables
$totalUsers = $totalDistributors = $totalRetailers = $totalAdmin = 0;
$todayRecharge = $monthRecharge = $todayCommission = $monthCommission = $wallet = 0;
$todayNsdl = $monthNsdl = $todayNsdlSuccess = $monthNsdlSuccess = $todayNsdlPending = $monthNsdlPending = 0;
$todayWalletCommission = $monthWalletCommission = 0;

// Fetch stats based on user type
if($userType == 'admin'){
    $wallet = $udata['balance'] ?? 0;
    $totalUsers = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT COUNT(*) as cnt FROM users WHERE type='retailer'"))['cnt'];
    $totalDistributors = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT COUNT(*) as cnt FROM users WHERE type='distributor'"))['cnt'];
    $totalAdmin = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT COUNT(*) as cnt FROM users WHERE type='admin'"))['cnt'];
    $activeUsers = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT COUNT(*) as cnt FROM users WHERE status='1'"))['cnt'];
    $inactiveUsers = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT COUNT(*) as cnt FROM users WHERE status='0'"))['cnt'];

} elseif($userType == 'distributor'){
    $wallet = $udata['balance'];
    $totalRetailers = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT COUNT(*) as cnt FROM users WHERE parent='$userid' AND type='retailer'"))['cnt'];

} elseif($userType == 'retailer'){
    $wallet = $udata['balance'];
}

// Fetch common stats
// Recharge & Commission
if($userType == 'admin'){
    $todayRecharge = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT SUM(amount) as amt FROM recharge_history WHERE DATE(date)='$today'"))['amt'] ?? 0;
    $monthRecharge = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT SUM(amount) as amt FROM recharge_history WHERE DATE(date)>='$monthStart'"))['amt'] ?? 0;
    $todayCommission = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT SUM(commission) as amt FROM recharge_history WHERE DATE(date)='$today'"))['amt'] ?? 0;
    $monthCommission = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT SUM(commission) as amt FROM recharge_history WHERE DATE(date)>='$monthStart'"))['amt'] ?? 0;

} elseif($userType == 'distributor'){
    $todayRecharge = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT SUM(r.amount) as amt FROM recharge_history r JOIN users u ON u.userid=r.userid WHERE u.parent='$userid' AND DATE(r.date)='$today'"))['amt'] ?? 0;
    $monthRecharge = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT SUM(r.amount) as amt FROM recharge_history r JOIN users u ON u.userid=r.userid WHERE u.parent='$userid' AND DATE(r.date)>='$monthStart'"))['amt'] ?? 0;
    $todayCommission = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT SUM(r.commission) as amt FROM recharge_history r JOIN users u ON u.userid=r.userid WHERE u.parent='$userid' AND DATE(r.date)='$today'"))['amt'] ?? 0;
    $monthCommission = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT SUM(r.commission) as amt FROM recharge_history r JOIN users u ON u.userid=r.userid WHERE u.parent='$userid' AND DATE(r.date)>='$monthStart'"))['amt'] ?? 0;

} elseif($userType == 'retailer'){
    $todayData = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT SUM(amount) as amt, SUM(commission) as comm FROM recharge_history WHERE userid='$userid' AND DATE(date)='$today'")) ?? ['amt'=>0,'comm'=>0];
    $monthData = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT SUM(amount) as amt, SUM(commission) as comm FROM recharge_history WHERE userid='$userid' AND DATE(date)>='$monthStart'")) ?? ['amt'=>0,'comm'=>0];
    $todayRecharge = $todayData['amt'] ?? 0;
    $todayCommission = $todayData['comm'] ?? 0;
    $monthRecharge = $monthData['amt'] ?? 0;
    $monthCommission = $monthData['comm'] ?? 0;
}

// Wallet Commission
$todayWalletCommission = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT SUM(amount) as amt FROM wallethistory WHERE userid='$userid' AND purpose LIKE '%Commission%' AND DATE(date)='$today'"))['amt'] ?? 0;
$monthWalletCommission = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT SUM(amount) as amt FROM wallethistory WHERE userid='$userid' AND purpose LIKE '%Commission%' AND DATE(date)>='$monthStart'"))['amt'] ?? 0;

// NSDL Stats
if($userType == 'admin'){
    $todayNsdl = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT COUNT(*) as cnt FROM nsdl_requests WHERE DATE(date)='$today'"))['cnt'] ?? 0;
    $monthNsdl = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT COUNT(*) as cnt FROM nsdl_requests WHERE DATE(date)>='$monthStart'"))['cnt'] ?? 0;
    $todayNsdlSuccess = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT COUNT(*) as cnt FROM nsdl_requests WHERE status='SUCCESS' AND DATE(date)='$today'"))['cnt'] ?? 0;
    $monthNsdlSuccess = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT COUNT(*) as cnt FROM nsdl_requests WHERE status='SUCCESS' AND DATE(date)>='$monthStart'"))['cnt'] ?? 0;
    $todayNsdlPending = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT COUNT(*) as cnt FROM nsdl_requests WHERE status='Pending' AND DATE(date)='$today'"))['cnt'] ?? 0;
    $monthNsdlPending = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT COUNT(*) as cnt FROM nsdl_requests WHERE status='Pending' AND DATE(date)>='$monthStart'"))['cnt'] ?? 0;

} else {
    $todayNsdl = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT COUNT(*) as cnt FROM nsdl_requests WHERE phone='$userid' AND DATE(date)='$today'"))['cnt'] ?? 0;
    $monthNsdl = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT COUNT(*) as cnt FROM nsdl_requests WHERE phone='$userid' AND DATE(date)>='$monthStart'"))['cnt'] ?? 0;
    $todayNsdlSuccess = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT COUNT(*) as cnt FROM nsdl_requests WHERE phone='$userid' AND status='SUCCESS' AND DATE(date)='$today'"))['cnt'] ?? 0;
    $monthNsdlSuccess = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT COUNT(*) as cnt FROM nsdl_requests WHERE phone='$userid' AND status='SUCCESS' AND DATE(date)>='$monthStart'"))['cnt'] ?? 0;
    $todayNsdlPending = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT COUNT(*) as cnt FROM nsdl_requests WHERE phone='$userid' AND status='Pending' AND DATE(date)='$today'"))['cnt'] ?? 0;
    $monthNsdlPending = mysqli_fetch_assoc(mysqli_query($tng_conn, "SELECT COUNT(*) as cnt FROM nsdl_requests WHERE phone='$userid' AND status='Pending' AND DATE(date)>='$monthStart'"))['cnt'] ?? 0;
}
?>

<!-- CSS for Stylish Dashboard -->
<style>
.summary-card {
    padding: 20px;
    border-radius: 12px;
    color: #fff;
    margin-bottom: 20px;
    text-align: center;
    font-family: 'Segoe UI', sans-serif;
}
.bg-wallet{background:#4CAF50;}
.bg-admin{background:#2196F3;}
.bg-distributor{background:#FF9800;}
.bg-users{background:#9C27B0;}
.bg-success{background:#00BCD4;}
.bg-info{background:#3F51B5;}
.bg-warning{background:#FFC107;}
.bg-primary{background:#673AB7;}
.bg-purple{background:#9C27B0;}
.bg-dark{background:#212121;}
.bg-nsdl-today{background:#FF5722;}
.bg-nsdl-month{background:#795548;}
.bg-nsdl-success-today{background:#8BC34A;}
.bg-nsdl-success-month{background:#CDDC39;}
.bg-nsdl-pending-today{background:#F44336;}
.bg-nsdl-pending-month{background:#E91E63;}
.summary-card h5{margin:0;font-size:24px;font-weight:bold;}
.summary-card small{font-size:14px;display:block;margin-top:5px;}
</style>

<!-- Dashboard Cards -->
<div class="row mt-4">
    <div class="col-lg-3 col-md-6 col-sm-6">
        <div class="summary-card bg-wallet">
            <h5><?= formatAmt($wallet) ?></h5>
            <small>Wallet Balance</small>
        </div>
    </div>
    
    <?php if($userType == 'admin'){ ?>
        <div class="col-lg-3 col-md-6 col-sm-6">
            <div class="summary-card bg-admin">
                <h5><?= $totalAdmin ?></h5>
                <small>Total Admin</small>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 col-sm-6">
            <div class="summary-card bg-distributor">
                <h5><?= $totalDistributors ?></h5>
                <small>Total Distributor</small>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 col-sm-6">
            <div class="summary-card bg-users">
                <h5><?= $totalUsers ?></h5>
                <small>Total Users</small>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 col-sm-6">
            <div class="summary-card bg-info">
                <h5><?= $inactiveUsers ?></h5>
                <small>Total Inacitve User</small>
            </div>
        </div>
        <div class="col-lg-3 col-md-6 col-sm-6">
            <div class="summary-card bg-danger">
                <h5><?= $activeUsers ?></h5>
                <small>Total Active Users</small>
            </div>
        </div>
    <?php } elseif($userType == 'distributor'){ ?>
        <div class="col-lg-3 col-md-6 col-sm-6">
            <div class="summary-card bg-users">
                <h5><?= $totalRetailers ?></h5>
                <small>Total Retailers</small>
            </div>
        </div>
    <?php } ?>
    
    <!-- Recharge & Commission -->
    <div class="col-lg-3 col-md-6 col-sm-6">
        <div class="summary-card bg-success">
            <h5><?= formatAmt($todayRecharge) ?></h5>
            <small>Today's Recharge</small>
        </div>
    </div>
    <div class="col-lg-3 col-md-6 col-sm-6">
        <div class="summary-card bg-info">
            <h5><?= formatAmt($monthRecharge) ?></h5>
            <small>This Month Recharge</small>
        </div>
    </div>
    <div class="col-lg-3 col-md-6 col-sm-6">
        <div class="summary-card bg-warning">
            <h5><?= formatAmt($todayCommission) ?></h5>
            <small>Today's Commission</small>
        </div>
    </div>
    <div class="col-lg-3 col-md-6 col-sm-6">
        <div class="summary-card bg-primary">
            <h5><?= formatAmt($monthCommission) ?></h5>
            <small>This Month Commission</small>
        </div>
    </div>

    <!-- Wallet Commission -->
    <div class="col-lg-3 col-md-6 col-sm-6">
        <div class="summary-card bg-purple">
            <h5><?= formatAmt($todayWalletCommission) ?></h5>
            <small>Today's Wallet Commission</small>
        </div>
    </div>
    <div class="col-lg-3 col-md-6 col-sm-6">
        <div class="summary-card bg-dark">
            <h5><?= formatAmt($monthWalletCommission) ?></h5>
            <small>This Month Wallet Commission</small>
        </div>
    </div>

    <!-- NSDL Stats -->
    <div class="col-lg-3 col-md-6 col-sm-6">
        <div class="summary-card bg-nsdl-today">
            <h5><?= $todayNsdl ?></h5>
            <small>Today's NSDL Requests</small>
        </div>
    </div>
    <div class="col-lg-3 col-md-6 col-sm-6">
        <div class="summary-card bg-nsdl-month">
            <h5><?= $monthNsdl ?></h5>
            <small>This Month NSDL Requests</small>
        </div>
    </div>
    <div class="col-lg-3 col-md-6 col-sm-6">
        <div class="summary-card bg-nsdl-success-today">
            <h5><?= $todayNsdlSuccess ?></h5>
            <small>Today's NSDL Success</small>
        </div>
    </div>
    <div class="col-lg-3 col-md-6 col-sm-6">
        <div class="summary-card bg-nsdl-success-month">
            <h5><?= $monthNsdlSuccess ?></h5>
            <small>This Month NSDL Success</small>
        </div>
    </div>
    <div class="col-lg-3 col-md-6 col-sm-6">
        <div class="summary-card bg-nsdl-pending-today">
            <h5><?= $todayNsdlPending ?></h5>
            <small>Today's NSDL Pending</small>
        </div>
    </div>
    <div class="col-lg-3 col-md-6 col-sm-6">
        <div class="summary-card bg-nsdl-pending-month">
            <h5><?= $monthNsdlPending ?></h5>
            <small>This Month NSDL Pending</small>
        </div>
    </div>
</div>


</div>
</div>

<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
function showUpdatePopup() {
    Swal.fire({
        title: '🚀 Update Available!',
        html: `
            <b>Current Version:</b> <?= $currentVersion ?><br>
            <b>New Version:</b> <?= $nextUpdate['version'] ?><br><br>
            <b>Changelog:</b><br><?= nl2br($nextUpdate['changelog']) ?>
        `,
        icon: 'info',
        showCancelButton: true,
        confirmButtonText: 'Yes, Update',
        cancelButtonText: 'Cancel',
        reverseButtons: true
    }).then((result) => {
        if(result.isConfirmed){
            Swal.fire({
                title: '⚠️ Are you sure?',
                text: 'The system will start updating. Make sure you have backed up your data!',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, Start Update',
                cancelButtonText: 'Cancel',
                reverseButtons: true
            }).then((confirmResult) => {
                if(confirmResult.isConfirmed){
                    applyUpdate();
                }
            });
        }
    });
}

function applyUpdate() {
    Swal.fire({
        title: '⏳ Updating...',
        html: `
            <div id="updateProgressContainer" style="width:100%;background:#f0f0f0;border-radius:8px;height:20px;margin-top:20px;">
                <div id="updateProgressBar" style="width:0%;height:100%;background:#4caf50;border-radius:8px;text-align:center;color:white;line-height:20px;">0%</div>
            </div>
            <div id="updateStatus" style="margin-top:15px;text-align:center;">Starting update...</div>
        `,
        showConfirmButton: false,
        allowOutsideClick: false,
        didOpen: () => {
            fetch('../update/update.php', {
                method: 'POST',
                body: JSON.stringify({
                    update_url: "<?= $nextUpdate['update_url'] ?>",
                    version: "<?= $nextUpdate['version'] ?>",
                    extractPath: "<?= $nextUpdate['extractPath'] ?>"
                }),
                headers: { 'Content-Type': 'application/json' }
            })
            .then(res => res.json())
            .then(data => {
                let progress = 0;
                const progressBar = document.getElementById('updateProgressBar');
                const statusText = document.getElementById('updateStatus');
                
                const interval = setInterval(() => {
                    progress += Math.floor(Math.random() * 10) + 5;
                    if(progress > 100) progress = 100;
                    progressBar.style.width = progress + '%';
                    progressBar.innerText = progress + '%';
                    
                    if(progress >= 100){
                        clearInterval(interval);
                        statusText.innerText = data.success ? 'Update Completed!' : 'Update Failed!';
                        Swal.fire({
                            title: data.success ? '✅ Update Successful' : '❌ Update Failed',
                            text: data.message,
                            icon: data.success ? 'success' : 'error'
                        }).then(() => {
                            if(data.success) location.reload();
                        });
                    }
                }, 300);
            })
            .catch(err => {
                Swal.fire('❌ Update Failed', err, 'error');
                console.error(err);
            });
        }
    });
}
</script>


<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/js/bootstrap.bundle.min.js"></script>
<?php include('../template/tngweb/footer.php'); ?>

<script src="../template/tngweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/tngweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../template/tngweb/assets/js/app.js"></script>
