<?php
// index.php
require_once 'auth.php'; 
check_access();

// گرفتن اطلاعات دسترسی کاربر
$access = get_user_access_config();
?>
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <title>نقشه جامع فروشگاه‌ها</title>
  <link rel="manifest" href="manifest.json">
  <link rel="icon" type="image/png" href="icon.png">
  <link rel="apple-touch-icon" href="icon.png">
  <meta name="theme-color" content="#333333">
  <link rel="stylesheet" href="assets/neshan/index.css" />
  <link rel="stylesheet" href="assets/css/MarkerCluster.css" />
  <link rel="stylesheet" href="assets/css/MarkerCluster.Default.css" />
  <link rel="stylesheet" href="style.css">
</head>
<body>

  <!-- Loading Screen -->
  <div class="loading-overlay" id="loading-overlay">
    <div class="loading-box">
      <div class="loading-spinner"></div>
      <div class="loading-text" id="loading-text">در حال آماده‌سازی...</div>
      <div class="progress-track">
        <div class="progress-fill" id="progress-bar"></div>
      </div>
      <div class="progress-percent" id="progress-percent">0%</div>
    </div>
  </div>

  <!-- Mobile Toggle -->
  <button id="mobile-menu-btn" class="mobile-menu-btn">
    <svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" stroke-width="2" fill="none">
      <line x1="3" y1="12" x2="21" y2="12"></line>
      <line x1="3" y1="6" x2="21" y2="6"></line>
      <line x1="3" y1="18" x2="21" y2="18"></line>
    </svg>
    فیلترها
  </button>

  <div class="container">
    <!-- Sidebar -->
    <aside class="sidebar" id="sidebar">
      <div class="sidebar-header">
        <h2>GeoInsight <small style="font-size:11px;opacity:0.6;font-weight:400">Location Intelligence</small></h2>
        <button class="close-sidebar-btn" id="close-sidebar">&times;</button>
      </div>
      
      <!-- نمایش اطلاعات کاربر -->
      <div class="user-info-bar" id="user-info-bar">
          <div class="user-info-content">
              <span class="user-icon">👤</span>
              <span class="user-display-name" id="user-display-name">
                  <?php echo htmlspecialchars($access['user_name']); ?>
              </span>
              <?php if ($access['role'] === 'area_supervisor'): ?>
                  <span class="user-role-badge area-sup">مدیر منطقه</span>
              <?php elseif ($access['role'] === 'regional_manager'): ?>
                  <span class="user-role-badge area-sup">مدیر ناحیه</span>
              <?php else: ?>
                  <span class="user-role-badge admin-badge">دسترسی کامل</span>
              <?php endif; ?>
          </div>
          <a href="logout.php" class="logout-link" title="خروج">⏻ خروج</a>
      </div>

      <div class="sidebar-content">
        <!-- Brands -->
        <div class="filter-section">
          <h3>برندها</h3>
          <div id="brand-list" class="brand-list"></div>
        </div>
        
        <!-- Filters -->
        <div class="dropdown-section">
          <h3>استان</h3>
          <div class="custom-select">
            <input type="text" class="select-search" id="state-search" placeholder="همه استان‌ها" autocomplete="off" />
            <div class="select-dropdown" id="state-dropdown"></div>
          </div>
        </div>
        
        <div class="dropdown-section">
          <h3>شهرستان</h3>
          <div class="custom-select">
            <input type="text" class="select-search" id="county-search" placeholder="ابتدا استان را انتخاب کنید..." autocomplete="off" disabled />
            <div class="select-dropdown" id="county-dropdown"></div>
          </div>
        </div>
        
        <div class="dropdown-section">
          <h3>سرپرست ناحیه (فقط دیلی)</h3>
          <div class="custom-select">
            <input type="text" class="select-search" id="supervisor-search" placeholder="همه سرپرست‌ها" autocomplete="off" />
            <div class="select-dropdown" id="supervisor-dropdown"></div>
          </div>
        </div>

        <!-- Toggles -->
        <div class="filter-section">
          <h3>نوع فروش (فقط دیلی)</h3>
          <div class="toggle-switch">
            <input type="radio" id="sales_all" name="sales_type" value="all" checked />
            <label for="sales_all">همه</label>

            <input type="radio" id="sales_online" name="sales_type" value="online" />
            <label for="sales_online">آنلاین</label>

            <input type="radio" id="sales_offline" name="sales_type" value="offline" />
            <label for="sales_offline">آفلاین</label>
          </div>
        </div>

        <div class="filter-section">
          <h3>منطقه ترافیکی</h3>
          <div class="toggle-switch">
            <input type="radio" id="traffic_all" name="traffic_zone" value="" checked />
            <label for="traffic_all">همه</label>
            <input type="radio" id="traffic_true" name="traffic_zone" value="TRUE" />
            <label for="traffic_true">داخل</label>
            <input type="radio" id="traffic_false" name="traffic_zone" value="FALSE" />
            <label for="traffic_false">خارج</label>
          </div>
        </div>
        
        <div class="filter-section">
          <h3>طرح زوج و فرد</h3>
          <div class="toggle-switch">
            <input type="radio" id="oddeven_all" name="oddeven_zone" value="" checked />
            <label for="oddeven_all">همه</label>
            <input type="radio" id="oddeven_true" name="oddeven_zone" value="TRUE" />
            <label for="oddeven_true">داخل</label>
            <input type="radio" id="oddeven_false" name="oddeven_zone" value="FALSE" />
            <label for="oddeven_false">خارج</label>
          </div>
        </div>
        
        <div class="filter-section">
          <h3>نوع مالکیت (فقط افق، دیلی و هفت)</h3>
          <div class="toggle-switch">
            <input type="radio" id="franchise_all" name="franchise" value="" checked />
            <label for="franchise_all">همه</label>
            <input type="radio" id="franchise_true" name="franchise" value="1" />
            <label for="franchise_true">فرانچایز</label>
            <input type="radio" id="franchise_false" name="franchise" value="0" />
            <label for="franchise_false">عادی</label>
          </div>
        </div>

        <div class="radius-control">
          <h3>شعاع دایره</h3>
          <div class="radius-slider-container">
            <span id="radius-value">250 متر</span>
            <input type="range" class="radius-slider" id="radius-slider" min="50" max="5000" step="50" value="250" />
          </div>
        </div>

        <div class="controls">
          <button id="toggle-cluster-btn" class="control-btn success">غیرفعال کردن کلاسترینگ</button>
          <button id="reset-filters-btn" class="control-btn reset">بازنشانی فیلترها</button>
          <button id="fit-bounds-btn" class="control-btn primary">نمایش کلی</button>
        </div>
      </div>
    </aside>

    <main id="map-container">
      <div id="map"></div>
      <!-- START: Store Search Box -->
      <div id="store-search-wrapper">
          <div id="store-search-container">
              <input type="text" id="store-code-input" placeholder="کد یا نام دیلی‌مارکت..." autocomplete="off" />
              <button id="store-search-btn">🔍</button>
          </div>
          <!-- لیست کشویی نتایج -->
          <ul id="search-results-dropdown"></ul>
      </div>
      <!-- END: Store Search Box -->

      <div class="info-panel">
        <div id="daily-details-box" class="details-card"></div>
        <div class="visible-stats">
            <h4>آمار فروشگاه‌های موجود در کادر</h4>
            <div id="info-display">در حال بارگذاری...</div>
        </div>
      </div>
    </main>
  </div>

  <!-- Template with Improved Rent Section -->
  <script id="details-template" type="text/template">
    <div class="dd-header">
        <h5 class="dd-title">{{store_name}}</h5>
        <span class="dd-badge">{{store_code}}</span>
    </div>
    <div class="dd-body">
        <div class="dd-meta-grid">
            <div class="dd-meta-item">
                <span class="dd-meta-label">سرپرست</span>
                <span class="dd-meta-val">{{supervisor_name}}</span>
            </div>
            <div class="dd-meta-item">
                <span class="dd-meta-label">تاریخ افتتاح</span>
                <span class="dd-meta-val">{{opening_date}}</span>
            </div>
        </div>
        
        <div class="dd-table-wrapper">
            <table class="details-table">
                <thead>
                    <tr>
                        <th>شرح</th>
                        <th>کل</th>
                        <th class="text-muted">آفلاین</th>
                        <th class="text-online">آنلاین</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td class="row-head">فروش کل</td>
                        <td class="fw-bold">{{total_sales}}</td>
                        <td>{{offline_sales}}</td>
                        <td class="text-online fw-bold">{{online_sales}}</td>
                    </tr>
                    <tr>
                        <td class="row-head">م. فروش روزانه</td>
                        <td class="fw-bold">{{avg_daily_sales}}</td>
                        <td>{{avg_daily_sales_offline}}</td>
                        <td class="text-online fw-bold">{{avg_daily_sales_online}}</td>
                    </tr>
                    <tr>
                        <td class="row-head">م. پاخور</td>
                        <td class="fw-bold">{{avg_daily_trans}}</td>
                        <td>{{avg_daily_trans_offline}}</td>
                        <td class="text-online fw-bold">{{avg_daily_trans_online}}</td>
                    </tr>
                    <tr>
                        <td class="row-head">م. ارزش سبد</td>
                        <td class="fw-bold">{{avg_basket}}</td>
                        <td>{{avg_basket_offline}}</td>
                        <td class="text-online fw-bold">{{avg_basket_online}}</td>
                    </tr>
                </tbody>
            </table>
        </div>
        
        <!-- Improved Rent Section -->
        <div class="rent-container">
            <div class="rent-header">اطلاعات اجاره</div>
            <div class="rent-main">
                <span class="rent-amount">{{rent_amount}}</span>
                <span class="rent-unit">ریال</span>
            </div>
            <div class="rent-details-grid">
                <div class="rent-box">
                    <span class="rent-val">{{rent_pct}}</span>
                    <span class="rent-lbl">نسبت به فروش</span>
                </div>
                <div class="rent-box">
                    <span class="rent-val">{{rent_ratio}}</span>
                    <span class="rent-lbl">نسبت به میانگین</span>
                </div>
            </div>
        </div>
    </div>
  </script>

  <script>
    window.MAP_CONFIG = {
      apiKey: "web.9ad57766da264d059892601d5b895aa4", 
      dailyCsv: "Daily_data.csv",
      totalCsv: "total.csv",
      haftCsv: "haft_data.csv"
    };
    
    window.USER_ACCESS = {
      role: "<?php echo htmlspecialchars($access['role']); ?>",
      area_supervisor_id: <?php echo $access['area_supervisor_id'] ? '"' . htmlspecialchars($access['area_supervisor_id']) . '"' : 'null'; ?>,
      area_supervisor_ids: <?php echo $access['area_supervisor_ids'] ? json_encode($access['area_supervisor_ids']) : 'null'; ?>,
      user_name: "<?php echo htmlspecialchars($access['user_name']); ?>"
    };
  </script>

  <script src="assets/neshan/index.js"></script>
  <script src="assets/js/leaflet.markercluster.js"></script>
  <script src="assets/js/papaparse.min.js"></script>
  <script src="script.js"></script>
  <script src="customcode.js"></script>
    <script src="search.js"></script> <!-- این خط اضافه شود -->

  <script src="activity_tracker.js"></script>

  <script>
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('./sw.js', { scope: './' })
        .then(reg => console.log('ServiceWorker registered'))
        .catch(err => console.log('ServiceWorker registration failed:', err));
    }
  </script>
</body>
</html>
