<?php
$db =& get_instance();
$CI =& get_instance();
$method = $CI->router->fetch_method();
$userdetails = $db->userdetails();
$products = $db->Product_model;
$notifications_count = $products->getnotificationnew_count('admin', null);
$payment_details = json_decode($plan->payment_details);
$loginUser = $_SESSION['user'];

$user_side_bar_clock_text_color = $products->getSettings('theme','user_side_bar_clock_text_color');
$PrimaryPaymentMethodStatus = $products->getUserPaymentMethodStatus($userdetails['id'],$userdetails['primary_payment_method']);
$paymentlist         = $products->getPaymentWarning();
if(empty($payment_methods) && ($method != 'purchase_plan' && $method !='user_reports')){
$payment_methods = $this->session->userdata('payment_methods');
}
$loginUser = $_SESSION['user'];
if(isset($loginUser['is_vendor']) && $loginUser['is_vendor'] == 1) {
$store_setting =$db->Product_model->getSettings('store');
$vendor_setting = $db->Product_model->getSettings('vendor');
$marketVendorStatus= $db->Product_model->getSettings('market_vendor', 'marketvendorstatus');
$vendoerMinDeposit = $db->Product_model->getSettings('site', 'vendor_min_deposit');
$userdepbal['vendor_min_deposit'] = isset($vendoerMinDeposit['vendor_min_deposit']) ? $vendoerMinDeposit['vendor_min_deposit'] : 0;

$db->load->model('Total_model');
$depbalence = $db->Total_model->getUserBalance($loginUser['id']);

$userdepbal['show_deposit_warning'] = ($depbalence < $userdepbal['vendor_min_deposit']) ? 1 : 0;
$userdepbal['vendor_min_deposit_warning'] = __('user.minimum_deposit_warning');

$vendorDepositStatus = $this->Product_model->getSettings('vendor', 'depositstatus');
$userdepbal['vendor_deposit_status'] = isset($vendorDepositStatus['depositstatus']) ? $vendorDepositStatus['depositstatus'] : 0;
}
?>

<div class="container-fluid">
  <div class="row g-4">

    <!-- Welcome Hero Section -->
    <div class="col-12 fade-in-up">
      <div class="text-white border-0 shadow-lg rounded-4 hero-animated-gradient position-relative overflow-hidden" style="background: var(--v14-hero-affiliate);">
        <div class="dashboard-welcome-pattern" style="position:absolute;top:0;right:0;width:40%;height:100%;background:url('data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 80 80%22><circle cx=%2240%22 cy=%2240%22 r=%2230%22 fill=%22rgba(255,255,255,0.03)%22/></svg>') repeat;pointer-events:none;"></div>
        <div class="p-4 p-md-5 position-relative">
          <div class="row align-items-center g-3">
            <div class="col-lg-7 col-md-7">
              <div class="d-flex align-items-center mb-3">
                <div class="border border-white border-opacity-30 rounded-circle p-2 me-3">
                  <img src="<?= $products->getAvatar($userdetails['avatar']); ?>" alt="" class="rounded-circle" width="56" height="56" />
                </div>
                <div>
                  <h2 class="mb-1 fw-bold">
                    <?php
                    $hour = (int)date('H');
                    if ($hour < 12) $greeting = __('user.good_morning');
                    elseif ($hour < 18) $greeting = __('user.good_afternoon');
                    else $greeting = __('user.good_evening');
                    ?>
                    <?= $greeting ?>, <?= htmlspecialchars($userdetails['firstname']) ?>! <span class="v14-badge">V14</span>
                  </h2>
                  <p class="mb-0 opacity-90">
                    <?= __('user.system_status') ?>: 
                    <span class="badge bg-success bg-opacity-25 text-white">
                      <i class="fas fa-check-circle me-1"></i><?= __('user.active') ?>
                    </span>
                  </p>
                </div>
              </div>
            </div>
            <div class="col-lg-5 col-md-5 text-lg-end text-center">
              <div class="d-flex gap-2 justify-content-lg-end justify-content-center flex-wrap">
                <a href="<?= base_url('usercontrol/analytics_dashboard') ?>" class="btn btn-light btn-lg px-4 py-2 fw-semibold btn-micro">
                  <i class="fas fa-chart-line me-2"></i><?= __('user.analytics') ?>
                </a>
                <a href="<?= base_url('usercontrol/mywallet') ?>" class="btn btn-outline-light btn-lg px-4 py-2 fw-semibold btn-micro">
                  <i class="fas fa-wallet me-2"></i><?= __('user.page_title_wallet') ?>
                </a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Balance Card Section -->
    <div class="col-12 card-animate" data-animate-index="1">
      <div class="card bg-white shadow-lg rounded-4 border-0 card-hover-lift stat-card-glow glow-blue">
        <div class="card-body p-4">
          <div class="row align-items-center">
            <div class="col-lg-8 col-md-7">
              <div class="d-flex align-items-center gap-4">
                <div class="bg-primary bg-opacity-10 rounded-circle p-4 d-flex align-items-center justify-content-center" style="width: 80px; height: 80px;">
                  <i class="fa-sharp fa-solid fa-money-bill-trend-up fs-1 text-primary"></i>
                </div>
                <div>
                  <p class="mb-1 text-muted fs-6 fw-medium"><?= __('user.available_balance') ?></p>
                  <h1 class="fw-bold mb-2"><?= $fun_c_format($user_totals['user_balance']) ?></h1>
                  <div class="badge bg-primary bg-opacity-10 text-primary fw-semibold">
                    <i class="fa-sharp fa-solid fa-arrow-up me-2"></i>
                    <?= __('user.total_paid_commission') ?> <?= $fun_c_format($user_totals['wallet_accept_amount']) ?>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-lg-4 col-md-5 text-lg-end text-center mt-4 mt-lg-0">
              <div class="d-flex gap-2 justify-content-lg-end justify-content-center flex-wrap">
                <a href="<?= base_url('usercontrol/mywallet') ?>" class="btn btn-outline-primary px-4 py-2 w-100 w-md-auto">
                  <i class="fas fa-wallet me-2"></i>
                  <?= __('user.page_title_wallet') ?>
                </a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- V14: Performance Overview with Sparklines & Ring Chart -->
    <?php if(isset($trends)): ?>
    <div class="col-12 card-animate" data-animate-index="2">
      <div class="row g-4">
        <div class="col-lg-4">
          <div class="card bg-white shadow-sm rounded-4 border-0 h-100 card-hover-lift performance-overview-card">
            <div class="card-body p-4">
              <h6 class="fw-bold mb-3"><i class="fas fa-chart-pie me-2" style="color:#8b5cf6"></i><?= __('user.performance_overview') ?></h6>
              <div class="ring-chart-container mx-auto">
                <canvas id="userRingChart"></canvas>
                <div class="ring-chart-center-text">
                  <div class="ring-value" style="color:var(--v14-text-primary)"><?= $fun_c_format($user_totals['user_balance']) ?></div>
                  <div class="ring-label text-muted"><?= __('user.balance') ?></div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="col-lg-8">
          <div class="card bg-white shadow-sm rounded-4 border-0 h-100 card-hover-lift">
            <div class="card-body p-4">
              <h6 class="fw-bold mb-3"><i class="fas fa-chart-area text-primary me-2"></i><?= __('user.seven_day_trends') ?></h6>
              <div class="row g-3">
                <div class="col-md-4">
                  <div class="p-3 rounded-3" style="background:var(--v14-stat-blue)">
                    <div class="d-flex justify-content-between align-items-center mb-1">
                      <small class="fw-semibold text-primary"><?= __('user.earnings') ?></small>
                      <small class="fw-bold"><?= $fun_c_format(array_sum($trends['commissions'])) ?></small>
                    </div>
                    <div class="sparkline-container"><canvas id="userSparkEarnings"></canvas></div>
                  </div>
                </div>
                <div class="col-md-4">
                  <div class="p-3 rounded-3" style="background:var(--v14-stat-purple)">
                    <div class="d-flex justify-content-between align-items-center mb-1">
                      <small class="fw-semibold" style="color:#8b5cf6"><?= __('user.clicks') ?></small>
                      <small class="fw-bold"><?= number_format(array_sum($trends['clicks'])) ?></small>
                    </div>
                    <div class="sparkline-container"><canvas id="userSparkClicks"></canvas></div>
                  </div>
                </div>
                <div class="col-md-4">
                  <div class="p-3 rounded-3" style="background:var(--v14-stat-green)">
                    <div class="d-flex justify-content-between align-items-center mb-1">
                      <small class="fw-semibold text-success"><?= __('user.conversions') ?></small>
                      <small class="fw-bold"><?= number_format(array_sum($trends['orders'])) ?></small>
                    </div>
                    <div class="sparkline-container"><canvas id="userSparkConversions"></canvas></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <?php endif; ?>

    <!-- Affiliate Links Card -->
    <div class="col-12 card-animate" data-animate-index="3">
      <div class="card border-0 shadow-lg rounded-4">
        <?php
        if($store['status'] || $refer_status):
        $invitationlinkid = 0;
        if(isset($userdashboard_settings) && isset($userdashboard_settings['invitation_link_id'])) {
        $invitationlinkidarray = $userdashboard_settings['invitation_link_id'];
        $invitationlinkid = $invitationlinkidarray['setting_value'];
        }

        if($invitationlinkid == 0):
        ?>
        <div class="card-header bg-warning text-dark border-0 py-4">
          <div class="d-flex justify-content-between align-items-center">
            <h4 class="card-title mb-0 d-flex align-items-center fw-bold">
            <i class="fas fa-link me-3"></i>
            <?= __('user.affiliate_name') ?>: <span class="ms-3 badge bg-light text-dark"><?= $userdetails['id'] ?></span>
            </h4>
            <div class="form-check form-switch">
              <input class="form-check-input" type="checkbox" id="show_my_id">
              <label class="form-check-label fw-medium" for="show_my_id"><?= __('user.show_my_id') ?></label>
            </div>
          </div>
        </div>
        <?php endif; endif; ?>

        <div class="card-body p-4">
          <?php if ($store['status'] || $refer_status): ?>

          <!-- ========== AFFILIATE STORE ========== -->
          <?php if ($store['status']): ?>
          <?php
          $base       = $store_slug ?: 'store/' . base64_encode($userdetails['id']);
          $tinyUrl    = base_url($base);                       // no ID
          $megaUrl    = $tinyUrl . '/?id=' . $userdetails['id']; // with ID
          $tinyHide   = $invitationlinkid == 1 ? 'd-none' : '';
          $megaHide   = $invitationlinkid == 0 ? 'd-none' : '';
          ?>
          <div class="mb-4 show-tiny-link <?= $tinyHide ?>">
            <label class="form-label fw-bold fs-5 mb-3"><i class="fas fa-store text-primary me-2"></i><?= __('user.store_url') ?></label>
            <?php linkRow('primary', $tinyUrl, 'input-store-url-0', 'store'); ?>
          </div>
          <div class="mb-4 show-mega-link <?= $megaHide ?>">
            <label class="form-label fw-bold fs-5 mb-3"><i class="fas fa-store text-primary me-2"></i><?= __('user.store_url') ?></label>
            <?php linkRow('primary', $megaUrl, 'input-store-mega-url-0', 'store'); ?>
          </div>
          <?php endif; ?>

          <!-- ========== VENDOR STORE ========== -->
          <?php if (!empty($vendor_store_slug)): ?>
          <?php
          $base       = 'store/' . $vendor_store_slug . '/' . base64_encode($userdetails['id']);
          $tinyUrl    = base_url($base);
          $megaUrl    = $tinyUrl . '/?id=' . $userdetails['id'];
          $tinyHide   = $invitationlinkid == 1 ? 'd-none' : '';
          $megaHide   = $invitationlinkid == 0 ? 'd-none' : '';
          ?>
          <div class="mb-4 show-tiny-link <?= $tinyHide ?>">
            <label class="form-label fw-bold fs-5 mb-3"><i class="fas fa-shopping-basket text-success me-2"></i><?= __('user.share_your_vendor_store') ?></label>
            <?php linkRow('success', $tinyUrl, 'input-storepage-url-0', 'vendor_store'); ?>
          </div>
          <div class="mb-4 show-mega-link <?= $megaHide ?>">
            <label class="form-label fw-bold fs-5 mb-3"><i class="fas fa-shopping-basket text-success me-2"></i><?= __('user.share_your_vendor_store') ?></label>
            <?php linkRow('success', $megaUrl, 'input-storepage-mega-url-0', 'vendor_store'); ?>
          </div>
          <?php endif; ?>

          <!-- ========== VENDOR INVITATION LINK ========== -->
          <?php if ($userdetails['is_vendor'] == 1 && $refer_status && allowMarketVendorPanelSections($marketvendorpanelmode,$userdetails['is_vendor'])): ?>
          <?php
          $base       = 'register/vendor/' . base64_encode($userdetails['id']);
          $tinyUrl    = base_url($base);
          $megaUrl    = $tinyUrl . '/?id=' . $userdetails['id'];
          $tinyHide   = $invitationlinkid == 1 ? 'd-none' : '';
          $megaHide   = $invitationlinkid == 0 ? 'd-none' : '';
          ?>
          <div class="mb-4 show-tiny-link <?= $tinyHide ?>">
            <label class="form-label fw-bold fs-5 mb-3"><i class="fas fa-user-tie text-warning me-2"></i><?= __('user.invite_people_to_become_vendors') ?></label>
            <?php linkRow('warning', $tinyUrl, 'input-vendor-url-0',      'vendor'); ?>
          </div>
          <div class="mb-4 show-mega-link <?= $megaHide ?>">
            <label class="form-label fw-bold fs-5 mb-3"><i class="fas fa-user-tie text-warning me-2"></i><?= __('user.invite_people_to_become_vendors') ?></label>
            <?php linkRow('warning', $megaUrl, 'input-vendor-mega-url-0', 'vendor'); ?>
          </div>
          <?php endif; ?>

          <!-- ========== REGISTER / REFERRAL LINK ========== -->
          <?php if ($refer_status && allowMarketVendorPanelSections($marketvendorpanelmode,$userdetails['is_vendor'])): ?>
          <?php
          $base       = $register_slug ?: 'register/' . base64_encode($userdetails['id']);
          $tinyUrl    = base_url($base);
          $megaUrl    = $tinyUrl . '/?id=' . $userdetails['id'];
          $tinyHide   = $invitationlinkid == 1 ? 'd-none' : '';
          $megaHide   = $invitationlinkid == 0 ? 'd-none' : '';
          ?>
          <div class="mb-4 show-tiny-link <?= $tinyHide ?>">
            <label class="form-label fw-bold fs-5 mb-3"><i class="fas fa-user-plus text-danger me-2"></i><?= __('user.invite_people_to_become_affiliates') ?></label>
            <?php linkRow('danger',   $tinyUrl, 'input-register-url-0',      'register'); ?>
          </div>
          <div class="mb-4 show-mega-link <?= $megaHide ?>">
            <label class="form-label fw-bold fs-5 mb-3"><i class="fas fa-user-plus text-danger me-2"></i><?= __('user.invite_people_to_become_affiliates') ?></label>
            <?php linkRow('danger',   $megaUrl, 'input-register-mega-url-0', 'register'); ?>
          </div>
          <?php endif; ?>

          <?php endif; /* end card */ ?>
        </div>

        <?php
        /* helper prints a single row */
        function linkRow($color, $url, $inputCls, $type){
        global $userdetails;
        ?>
        <div class="input-group input-group-lg">
          <input type="text" readonly value="<?= $url ?>" class="form-control bg-light <?= $inputCls ?> fs-6">
          <!-- copy button -->
          <button class="btn btn-<?= $color ?> copy-btn px-3" data-clipboard="<?= $url ?>"><i class="far fa-copy"></i></button>
          <!-- dropdown -->
          <button class="btn btn-<?= $color ?> dropdown-toggle dropdown-toggle-split px-3" data-bs-toggle="dropdown"></button>
          <ul class="dropdown-menu dropdown-menu-end">
          <!-- QR code (added) -->
          <li>
          <a class="dropdown-item qrcode" href="javascript:void(0)" data-id="<?= $url ?>">
          <i class="fas fa-qrcode me-2"></i><?= __('user.generate_qr_code') ?>
          </a>
          </li>
          <li>
          <a class="dropdown-item target-share-link" href="<?= $url ?>" target="_blank">
          <i class="fas fa-external-link-alt me-2"></i><?= __('user.open_link') ?>
          </a>
          </li>
          <li>
          <a class="dropdown-item dashboard-model-slug" href="javascript:void(0)"
          data-type="<?= $type ?>" data-related-id="0" data-input-class="<?= $inputCls ?>">
          <i class="fas fa-cog me-2"></i><?= __('user.customize') ?>
          </a>
          </li>
          <li>
          <a class="dropdown-item" href="javascript:void(0)"
          data-social-share data-share-url="<?= $url ?>?id=<?= $userdetails['id'] ?>">
          <i class="fas fa-share-alt me-2"></i><?= __('user.share') ?>
          </a>
          </li>
          </ul>
        </div>
        <?php } ?>
      </div>
    </div>

    <!-- Top Affiliates Card -->
    <?php if(isShowUserControlParts($userdashboard_settings['top_affiliate']) && allowMarketVendorPanelSections($marketvendorpanelmode, $userdetails['is_vendor'])): ?>
    <div class="col-12">
      <div class="card border-0 shadow-lg rounded-4">
        <div class="card-header bg-dark text-white border-0 py-4">
          <h4 class="card-title mb-0 d-flex align-items-center fw-bold">
          <i class="fas fa-trophy me-3"></i>
          <?= __('user.popular_affiliates') ?>
          </h4>
        </div>

        <div class="card-body p-0">
          <div class="table-responsive">
            <table class="table table-hover mb-0 align-middle">
            <thead class="table-light">
            <tr>
            <th class="py-4 px-4 fw-semibold"><?= __('user.name') ?></th>
            <th class="text-center py-4 fw-semibold"><?= __('user.country') ?></th>
            <th class="text-end py-4 px-4 fw-semibold"><?= __('user.commission') ?></th>
            </tr>
            </thead>
            <tbody>
            <?php foreach ($populer_users as $key => $users):
            $flag = '';
            if($users['sortname'] != '')
            $flag = base_url('assets/vertical/assets/images/flags/' . strtolower($users['sortname']) . '.png');

            $username = $users['firstname'].' '.$users['lastname'];
            if(strlen($username) > 12){
            $username = substr($username, 0, 12).'...';
            }
            ?>
            <tr>
            <td class="px-4">
            <div class="d-flex align-items-center">
              <img src="<?= $products->getAvatar($users['avatar']) ?>" class="rounded-circle me-3" width="40" height="40" alt="User Avatar">
              <span class="fw-medium fs-6"><?= htmlspecialchars($username) ?></span>
            </div>
            </td>
            <td class="text-center">
            <?php if($flag): ?>
            <img src="<?= $flag ?>" class="rounded" width="28" height="20" alt="<?= __('user.flag') ?>">
            <?php else: ?>
            <span class="text-muted">-</span>
            <?php endif; ?>
            </td>
            <td class="text-end px-4 fw-bold text-danger fs-6">
            <?= $fun_c_format($users['all_commition']); ?>
            </td>
            </tr>
            <?php endforeach; ?>

            <?php if(empty($populer_users)): ?>
            <tr>
            <td colspan="3" class="text-center py-5 text-muted">
            <i class="fas fa-users me-2 fs-4"></i>
            <span class="fs-5"><?= __('user.no_affiliate_activity_yet') ?></span>
            </td>
            </tr>
            <?php endif; ?>
            </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
    <?php endif; ?>

  </div>
</div>

<!-- QR Code Modal -->
<div class="modal fade" id="model-codemodal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered scanner">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title exampleModalLabel2"><?= __('user.scanner') ?></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body py-4">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" aria-label="Close">
          <i class="fas fa-times me-2"></i><?= __('user.close') ?>
        </button>
        <button type="button" class="btn btn-primary" id="download-qr-btn">
          <i class="fas fa-download me-2"></i><?= __('user.download') ?>
        </button>
        <button type="button" class="btn btn-success" id="print-qr-btn">
          <i class="fas fa-print me-2"></i><?= __('user.print') ?>
        </button>
      </div>
    </div>
  </div>
</div>

<!-- Slug Customization Modal -->
<div class="modal fade" id="slugtting" data-backdrop="static" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <form action="<?= base_url('/usercontrol/create_slug') ?>" method="post">
        <div class="modal-header">
          <h5 class="modal-title exampleModalLabel1"><?= __('user.create_slug'); ?></h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div class="slug-wrapp">
            <div class="form-group">
              <label class="form-label" for="exampleInputText1"><?= __('user.slug'); ?></label>
              <input type="text" name="slug" class="form-control" placeholder="<?= __('user.enter_slug_here') ?>">
              <input type="hidden" name="type" />
              <input type="hidden" name="related_id" />
              <input type="hidden" name="target" />
            </div>
            <div class="link-area align-items-center slug-url d-flex gap-2">
              <input type="text" readonly="readonly" class="form-control">
              <a class="bt-all btn btn-warning" href="javascript:void(0)" title="<?= __('user.copied'); ?>">
                <span class="btn-inner">
                  <i class="far fa-copy" alt="<?= __('user.copy') ?>"></i>
                </span>
              </a>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="submit" class="btn btn-secondary"><?= __('user.create'); ?></button>
          <button type="button" class="btn btn-primary" data-bs-dismiss="modal" aria-label="Close"><?= __('user.close'); ?></button>
          <button type="button" class="btn btn-primary btn-delete-slug"><?= __('user.delete'); ?></button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Welcome Modal -->
<?php
if (isset($welcome) && $welcome['show_popup'] == 'enable'):
    $welcome_shown = $this->session->userdata('dashboard_welcome_shown');
    $force_show = isset($_GET['show_welcome']) && $_GET['show_welcome'] == '1';
    
    if (!$welcome_shown || $force_show):
        // Parse video link
        $video_link = $welcome['video_link'] ?? '';
        $embed_url = '';
        if (!empty($video_link)) {
            if (preg_match('/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([^&\?\/]+)/', $video_link, $matches)) {
                $embed_url = 'https://www.youtube.com/embed/' . $matches[1];
            }
        }
?>
<div class="modal fade" id="welcomeModal" tabindex="-1" aria-labelledby="welcomeModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <div class="modal-content border-0 shadow-lg">
      <div class="modal-header bg-primary text-white border-0">
        <h5 class="modal-title fw-bold" id="welcomeModalLabel">
          <i class="fas fa-hand-wave me-2"></i><?= !empty($welcome['heading']) ? htmlspecialchars($welcome['heading']) : __('user.welcome_to_dashboard') ?>
        </h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body p-4">
        <?php if (!empty($embed_url)): ?>
        <div class="ratio ratio-16x9 mb-4">
          <iframe src="<?= $embed_url ?>" title="<?= htmlspecialchars($welcome['heading']) ?>" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen class="rounded"></iframe>
        </div>
        <?php endif; ?>

        <?php if (!empty($welcome['content'])): ?>
        <div class="alert alert-info border-0 mb-0" role="alert">
          <div class="d-flex align-items-start">
            <i class="fas fa-info-circle fs-4 me-3 mt-1 flex-shrink-0"></i>
            <div class="flex-grow-1"><?= nl2br(htmlspecialchars($welcome['content'])) ?></div>
          </div>
        </div>
        <?php endif; ?>
      </div>
      <div class="modal-footer border-0 bg-light">
        <button type="button" class="btn btn-secondary" id="welcomeDontShowAgain">
          <i class="fas fa-times-circle me-1"></i><?= __('user.dont_show_again') ?>
        </button>
        <button type="button" class="btn btn-primary" data-bs-dismiss="modal">
          <i class="fas fa-check me-1"></i><?= __('user.get_started') ?>
        </button>
      </div>
    </div>
  </div>
</div>

<script>
// Auto-show welcome modal on page load
$(document).ready(function() {
    $('#welcomeModal').modal('show');
    
    // Don't show again button - only this sets the session flag
    $('#welcomeDontShowAgain').on('click', function() {
        $.post('<?= base_url("usercontrol/set_welcome_shown") ?>', function() {
            console.log('Welcome modal marked as "don\'t show again"');
            $('#welcomeModal').modal('hide');
        });
    });
    
    // Regular close (Get Started or X button) doesn't set session
    // So popup will show again on next dashboard visit
});
</script>
<?php 
    endif; // End welcome_shown check
endif; // End show_popup check
?>

<!-- AI Suggestion Panel -->
<?php
$hide_forever = $this->session->userdata('hide_ai_box_forever');
$hide_temporarily = $this->session->userdata('hide_ai_box');
$settings = $this->Product_model->getSettings('userdashboard');
$ai_enabled = isset($settings['ai_suggestion_enabled']) ? $settings['ai_suggestion_enabled'] : '1';

if (!$hide_forever && $ai_enabled == '1'):
?>
<!-- AI Button -->
<button type="button" id="ai-suggestion-toggle" class="btn btn-primary rounded-circle position-fixed d-flex align-items-center justify-content-center" style="bottom: 20px; right: 20px; width: 50px; height: 50px; z-index: 1050;">
<i class="fas fa-robot"></i>
</button>

<!-- AI Side Panel -->
<div id="ai-suggestion-panel" class="position-fixed top-0 end-0 bg-white shadow-lg" style="width: 350px; max-width: 100%; height: 100vh; z-index: 1060; transform: translateX(100%); transition: transform 0.3s ease-in-out;">
  <!-- Header -->
  <div class="bg-primary text-white px-3 py-3 d-flex align-items-center justify-content-between">
    <div class="d-flex align-items-center">
      <i class="fas fa-robot me-2"></i>
      <span class="fw-bold"><?= __('user.assistant_title') ?></span>
    </div>
    <button type="button" class="btn-close btn-close-white" id="ai-suggestion-close" aria-label="<?= __('user.close') ?>"></button>
  </div>
  <!-- Content -->
  <div class="p-3">
    <div id="ai-suggestion-text" class="mb-3 min-vh-25">
      <div class="d-flex align-items-center text-muted">
        <div class="spinner-border spinner-border-sm me-2" role="status">
          <span class="visually-hidden"><?= __('user.loading') ?></span>
        </div>
        <span><?= __('user.loading') ?></span>
      </div>
    </div>
    <div class="text-center mb-2">
      <span class="badge bg-light text-muted fst-italic px-3 py-2"> <?= __('user.powered') ?> </span>
    </div>
  </div>
  <!-- Footer -->
  <div class="border-top p-3">
    <div class="row g-2">
      <div class="col-6">
        <button type="button" id="ai-suggestion-refresh" class="btn btn-outline-primary btn-sm w-100 d-flex align-items-center justify-content-center">
        <i class="fas fa-sync-alt me-1"></i>
        <span><?= __('user.new_suggestion') ?></span>
        </button>
      </div>
      <div class="col-6">
        <button type="button" id="ai-suggestion-dismiss" class="btn btn-outline-secondary btn-sm w-100 d-flex align-items-center justify-content-center">
        <i class="fas fa-times me-1"></i>
        <span><?= __('user.dismiss') ?></span>
        </button>
      </div>
    </div>
    <div class="text-center mt-2">
      <button type="button" id="ai-suggestion-hide-forever" class="btn btn-link btn-sm text-muted">
      <?= __('user.hide_forever') ?>
      </button>
    </div>
  </div>
</div>
<?php endif; ?>

<!-- Social Share Modal -->
<?= $social_share_modal ?>

<script>
document.addEventListener('DOMContentLoaded', function() {
const aiToggle = document.getElementById('ai-suggestion-toggle');
const aiPanel = document.getElementById('ai-suggestion-panel');
const aiClose = document.getElementById('ai-suggestion-close');
const aiText = document.getElementById('ai-suggestion-text');
const aiCounter = document.getElementById('ai-suggestion-counter');
const aiRefresh = document.getElementById('ai-suggestion-refresh');
const aiDismiss = document.getElementById('ai-suggestion-dismiss');
const aiHideForever = document.getElementById('ai-suggestion-hide-forever');
let currentSuggestionIndex = -1;
let isLoading = false;

if (!aiPanel || !aiToggle) return;

function openPanel() {
aiPanel.style.transform = 'translateX(0)';
loadSuggestion();
}
function closePanel() {
aiPanel.style.transform = 'translateX(100%)';
}

function loadSuggestion() {
if (isLoading) return;
isLoading = true;
aiText.innerHTML = `<div class="d-flex align-items-center text-muted"><div class="spinner-border spinner-border-sm me-2" role="status"><span class="visually-hidden"><?= __('user.loading') ?></span>
</div><span><?= __('user.loading') ?></span>
</div>`;
const formData = new FormData();
formData.append('action', 'get');
fetch('<?= base_url('usercontrol/ai_suggestion'); ?>', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
isLoading = false;
if (data.error) {
aiText.innerHTML = `<p class="text-danger">${data.error}</p>`;
return;
}
currentSuggestionIndex = data.index;
aiText.innerHTML = `<p>${data.suggestion}</p>`;
if (data.total > 0) {
if(aiCounter) aiCounter.textContent = `${data.index + 1} <?= __('user.of') ?> ${data.total}`;
}
})
.catch(error => {
isLoading = false;
aiText.innerHTML = `<p class="text-danger"><?= __('user.loading_error') ?></p>`;
});
}

function refreshSuggestion() {
if (isLoading) return;
isLoading = true;
aiText.innerHTML = `<div class="d-flex align-items-center text-muted"><div class="spinner-border spinner-border-sm me-2" role="status"><span class="visually-hidden"><?= __('user.loading') ?></span>
</div><span><?= __('user.loading_new') ?></span>
</div>`;
const formData = new FormData();
formData.append('action', 'refresh');
formData.append('current_index', currentSuggestionIndex);
fetch('<?= base_url('usercontrol/ai_suggestion'); ?>', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
isLoading = false;
if (data.error) {
aiText.innerHTML = `<p class="text-danger">${data.error}</p>`;
return;
}
currentSuggestionIndex = data.index;
aiText.innerHTML = `<p>${data.suggestion}</p>`;
if (data.total > 0) {
if(aiCounter) aiCounter.textContent = `${data.index + 1} <?= __('user.of') ?> ${data.total}`;
}
})
.catch(error => {
isLoading = false;
aiText.innerHTML = `<p class="text-danger"><?= __('user.refresh_error') ?></p>`;
});
}

function dismissSuggestion() {
const formData = new FormData();
formData.append('action', 'dismiss');
fetch('<?= base_url('usercontrol/ai_suggestion'); ?>', {
method: 'POST',
body: formData
});
closePanel();
}

function hideSuggestionForever() {
const formData = new FormData();
formData.append('action', 'hide_forever');
fetch('<?= base_url('usercontrol/ai_suggestion'); ?>', {
method: 'POST',
body: formData
});
closePanel();
aiToggle.style.display = 'none';
}

// Add missing dropdown functionality
$(document).ready(function() {
    // Enhanced QR Code functionality
    let currentQRCode = null;
    let currentQRUrl = '';

    $(document).on('click', '.qrcode', function() {
        currentQRUrl = $(this).attr('data-id');
        
        // Clear previous QR code and show loading
        $('#model-codemodal .modal-body').html(`
            <div class="d-flex flex-column align-items-center">
                <div class="spinner-border text-primary mb-2" role="status">
                    <span class="visually-hidden"><?= __('user.loading') ?></span>
                </div>
                <small class="text-muted"><?= __('user.generating_qr_code') ?></small>
            </div>
        `);
        
        // Set modal title
        $("#modal-title").text('<?= __('user.generate_qr_code') ?>');
        
        // Show modal
        $("#model-codemodal").modal("show");
        
        // Generate QR code after a short delay to show loading state
        setTimeout(() => {
            try {
                // Clear loading state and create container
                $('#model-codemodal .modal-body').html(`
                    <div id="qr-code-container" class="mb-3 d-flex justify-content-center align-items-center" style="min-height: 200px;"></div>
                    <div id="qr-url-display" class="text-muted small mb-3 px-3 text-break" style="max-height: 60px; overflow-y: auto;">${currentQRUrl}</div>
                    <div class="text-muted small">
                        <i class="fas fa-info-circle me-1"></i>
                        <?= __('user.scan_with_phone_camera') ?>
                    </div>
                `);
                
                // Generate QR code with improved size and mobile optimization
                const qrSize = window.innerWidth < 768 ? 180 : 220; // Responsive size
                
                currentQRCode = new QRCode(document.getElementById("qr-code-container"), {
                    text: currentQRUrl,
                    width: qrSize,
                    height: qrSize,
                    colorDark: "#000000",
                    colorLight: "#ffffff",
                    correctLevel: QRCode.CorrectLevel.H
                });
                
            } catch(error) {
                console.error('QR Code generation failed:', error);
                $('#model-codemodal .modal-body').html(`
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <?= __('user.qr_generation_failed') ?>
                    </div>
                `);
            }
        }, 300); // 300ms delay to show loading state
    });

    // Download QR Code functionality
    $(document).on('click', '#download-qr-btn', function() {
        if (!currentQRCode) return;
        
        try {
            const canvas = $('#qr-code-container canvas')[0];
            if (canvas) {
                // Create download link
                const link = document.createElement('a');
                link.download = 'qrcode-' + Date.now() + '.png';
                link.href = canvas.toDataURL();
                link.click();
            }
        } catch(error) {
            console.error('QR Code download failed:', error);
            alert('<?= __('user.download_failed') ?>');
        }
    });

    // Print QR Code functionality
    $(document).on('click', '#print-qr-btn', function() {
        if (!currentQRCode) return;
        
        try {
            const canvas = $('#qr-code-container canvas')[0];
            if (canvas) {
                const printWindow = window.open('', '_blank');
                printWindow.document.write(`
                    <html>
                        <head>
                            <title>QR Code - ${currentQRUrl}</title>
                            <style>
                                body { text-align: center; font-family: Arial, sans-serif; margin: 40px; }
                                .qr-container { margin: 20px 0; }
                                .url-text { margin-top: 20px; word-break: break-all; color: #666; }
                            </style>
                        </head>
                        <body>
                            <h2><?= __('user.qr_code') ?></h2>
                            <div class="qr-container">
                                <img src="${canvas.toDataURL()}" alt="QR Code" />
                            </div>
                            <div class="url-text">${currentQRUrl}</div>
                        </body>
                    </html>
                `);
                printWindow.document.close();
                printWindow.print();
            }
        } catch(error) {
            console.error('QR Code print failed:', error);
            alert('<?= __('user.print_failed') ?>');
        }
    });

    // Show/Hide ID toggle functionality
    $("#show_my_id").change(function() {
        if ($(this).prop("checked")) {
            $(".show-mega-link").removeClass("d-none");
            $(".show-tiny-link").addClass("d-none");
        } else {
            $(".show-mega-link").addClass("d-none");
            $(".show-tiny-link").removeClass("d-none");
        }
    });
});

aiToggle.addEventListener('click', openPanel);
aiClose.addEventListener('click', closePanel);
aiRefresh?.addEventListener('click', refreshSuggestion);
aiDismiss?.addEventListener('click', dismissSuggestion);
aiHideForever?.addEventListener('click', hideSuggestionForever);
});
</script>

<!-- Chart.js for Sparklines & Ring Charts -->
<script src="<?= base_url('assets/template/js/chart.umd.min.js') ?>?v=<?= av() ?>"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    <?php if(isset($trends)): ?>
    var trendData = <?= json_encode($trends) ?>;
    createSparkline('userSparkEarnings', trendData.commissions, '#0d6efd', 'rgba(13,110,253,0.15)');
    createSparkline('userSparkClicks', trendData.clicks, '#8b5cf6', 'rgba(139,92,246,0.15)');
    createSparkline('userSparkConversions', trendData.orders, '#198754', 'rgba(25,135,84,0.15)');

    // Ring Chart - Commission breakdown
    var saleComm = <?= (float)($user_totals['external_sale_total'] ?? 0) ?>;
    var clickComm = <?= (float)($user_totals['external_click_total'] ?? 0) ?>;
    var storeComm = <?= (float)($user_totals['localstore_sale_total'] ?? 0) ?>;
    createRingChart('userRingChart',
        ['<?= addslashes(__('user.sale_commission')) ?>', '<?= addslashes(__('user.click_commission')) ?>', '<?= addslashes(__('user.store_commission')) ?>'],
        [saleComm, clickComm, storeComm],
        ['#3b82f6', '#8b5cf6', '#22c55e']
    );
    <?php endif; ?>
});
</script>

