<?php
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/auth.php';
require_login();
require_role(['admin', 'production_manager', 'store_user']);

$user = current_user();
$role = $user['role'];
$userStoreId = $user['store_id'] ?? null;

if (empty($_SESSION['_csrf_token'])) csrf_token();

if ($role === 'store_user') {
    $stmt = db()->prepare("SELECT * FROM stores WHERE id = :id AND is_active = 1");
    $stmt->execute(['id' => $userStoreId]);
    $stores = $stmt->fetchAll();
} else {
    $stores = db()->query("SELECT * FROM stores WHERE is_active = 1 ORDER BY store_code")->fetchAll();
}

try {
    if ($role === 'store_user') {
        $stmt = db()->prepare("
            SELECT cil.*, s.store_code, u.full_name AS uploader
            FROM csv_import_logs cil
            JOIN stores s ON s.id = cil.store_id
            LEFT JOIN users u ON u.id = cil.uploaded_by
            WHERE cil.store_id = :store_id
            ORDER BY cil.created_at DESC
            LIMIT 10
        ");
        $stmt->execute(['store_id' => $userStoreId]);
        $history = $stmt->fetchAll();

        $stmt = db()->prepare("
            SELECT cil.*, s.store_code, COUNT(r.id) AS preview_rows
            FROM csv_import_logs cil
            JOIN stores s ON s.id = cil.store_id
            JOIN csv_import_rows r ON r.last_seen_import_log_id = cil.id AND r.row_status = 'store_pending'
            WHERE cil.store_id = :store_id
            GROUP BY cil.id
            ORDER BY cil.created_at DESC
            LIMIT 5
        ");
        $stmt->execute(['store_id' => $userStoreId]);
        $pendingPreviews = $stmt->fetchAll();
    } else {
        $history = db()->query("
            SELECT cil.*, s.store_code, u.full_name AS uploader
            FROM csv_import_logs cil
            JOIN stores s ON s.id = cil.store_id
            LEFT JOIN users u ON u.id = cil.uploaded_by
            ORDER BY cil.created_at DESC
            LIMIT 10
        ")->fetchAll();

        $pendingPreviews = db()->query("
            SELECT cil.*, s.store_code, COUNT(r.id) AS preview_rows
            FROM csv_import_logs cil
            JOIN stores s ON s.id = cil.store_id
            JOIN csv_import_rows r ON r.last_seen_import_log_id = cil.id AND r.row_status = 'store_pending'
            GROUP BY cil.id
            ORDER BY cil.created_at DESC
            LIMIT 8
        ")->fetchAll();
    }
} catch (Throwable $e) {
    $history = [];
    $pendingPreviews = [];
}

$flash = $_SESSION['flash'] ?? null;
unset($_SESSION['flash']);

$page_title = 'CSV Yükle';
$active_menu = 'csv';
include __DIR__ . '/includes/layout.php';
?>

<div class="ph">
  <div>
    <h1>CSV Yükle</h1>
    <p>Etsy <strong>Order Items CSV</strong> dosyasını yükleyip önizleyin. Orders CSV kullanılmayacak.</p>
  </div>
  <?php if (in_array($role, ['admin','production_manager'], true)): ?>
    <a href="admin_import_review.php" class="btn btn-secondary">CSV Onayları</a>
  <?php endif; ?>
</div>

<?php if ($flash): ?>
  <div class="alert <?= ($flash['type'] ?? '') === 'error' ? 'alert-danger' : 'alert-info' ?>">
    <span class="alert-ico"><?= ($flash['type'] ?? '') === 'error' ? '⚠' : 'ℹ' ?></span>
    <div><?= htmlspecialchars($flash['msg'] ?? '') ?></div>
  </div>
<?php endif; ?>

<?php if (!empty($pendingPreviews)): ?>
  <div class="card mb16">
    <div class="card-header">
      <span class="card-title">Devam Eden CSV Önizlemeleri</span>
    </div>
    <div class="card-body">
      <div class="alert alert-info">
        <span class="alert-ico">ℹ</span>
        <div>Önizleme artık veritabanında saklanır. Başka sayfaya geçseniz bile aşağıdan devam edebilirsiniz.</div>
      </div>
      <div class="table-wrap">
        <table>
          <thead>
            <tr>
              <th>Tarih</th>
              <th>Mağaza</th>
              <th>Dosya</th>
              <th class="tr">Bekleyen Satır</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
          <?php foreach ($pendingPreviews as $p): ?>
            <tr>
              <td class="mn"><?= htmlspecialchars($p['created_at']) ?></td>
              <td><span class="badge bg-gld"><?= htmlspecialchars($p['store_code']) ?></span></td>
              <td><?= htmlspecialchars($p['original_filename'] ?: $p['filename']) ?></td>
              <td class="tr"><?= (int)$p['preview_rows'] ?></td>
              <td class="tr"><a class="btn btn-secondary" href="csv_preview.php?log_id=<?= (int)$p['id'] ?>">Önizlemeye Devam Et</a></td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
<?php endif; ?>

<div style="max-width:760px">
  <div class="card">
    <div class="card-header">
      <span class="card-title">Etsy Order Items CSV</span>
    </div>
    <div class="card-body">
      <div class="alert alert-info">
        <span class="alert-ico">ℹ</span>
        <div>
          Etsy Shop Manager → Orders &amp; Shipping → Export → <strong>Order Items</strong>.
          Sistem CSV’yi önce veritabanında önizleme olarak saklar; onaylamadan üretime aktarmaz.
        </div>
      </div>

      <form method="post" action="csv_process.php" enctype="multipart/form-data" id="csvUploadForm">
        <?= csrf_field() ?>

        <?php if ($role === 'store_user'): ?>
          <input type="hidden" name="store_id" value="<?= (int)$userStoreId ?>">
          <div class="form-group">
            <label class="form-label">Mağaza</label>
            <div class="form-control" style="cursor:default">
              <span class="badge bg-gld"><?= htmlspecialchars($user['store_code'] ?? '') ?></span>
              <?= htmlspecialchars($user['store_name'] ?? '') ?>
            </div>
          </div>
        <?php else: ?>
          <div class="form-group">
            <label class="form-label">Mağaza <span class="req">*</span></label>
            <select name="store_id" class="form-control" required>
              <option value="">Mağaza seçin…</option>
              <?php foreach ($stores as $store): ?>
                <option value="<?= (int)$store['id'] ?>"><?= htmlspecialchars($store['store_code'].' — '.$store['store_name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
        <?php endif; ?>

        <div class="form-group">
          <label class="form-label">CSV Dosyası <span class="req">*</span></label>
          <div class="file-drop" id="csvDropZone" role="button" tabindex="0">
            <div class="file-drop-icon">📄</div>
            <div class="file-drop-text" id="fileDropText">Dosya seçmek için tıklayın veya CSV’yi buraya sürükleyip bırakın</div>
            <div class="file-drop-hint">Yalnızca .csv — Etsy Order Items CSV</div>
          </div>
          <input type="file" id="csvFile" name="csv_file" accept=".csv,text/csv" style="display:none" required>
        </div>

        <button type="submit" class="btn btn-primary btn-lg">↑ Önizlemeye Geç</button>
        <a href="dashboard.php" class="btn btn-secondary btn-lg">Vazgeç</a>
      </form>
    </div>
  </div>
</div>

<div class="card">
  <div class="card-header">
    <span class="card-title">Son CSV İşlemleri</span>
  </div>
  <?php if (!$history): ?>
    <div class="empty">
      <div class="empty-ico">∅</div>
      <div class="empty-title">Henüz CSV yüklenmedi</div>
      <div class="empty-text">İlk CSV yüklemeniz burada listelenecek.</div>
    </div>
  <?php else: ?>
    <div class="table-wrap">
      <table>
        <thead>
          <tr>
            <th>Tarih</th>
            <th>Mağaza</th>
            <th>Dosya</th>
            <th class="tr">CSV Satır</th>
            <th class="tr">Önizleme Satırı</th>
            <th>Durum</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($history as $row): ?>
          <tr>
            <td class="mn"><?= htmlspecialchars($row['created_at']) ?></td>
            <td><span class="badge bg-gld"><?= htmlspecialchars($row['store_code']) ?></span></td>
            <td><?= htmlspecialchars($row['original_filename'] ?: $row['filename']) ?></td>
            <td class="tr"><?= (int)$row['total_rows'] ?></td>
            <td class="tr"><?= (int)$row['inserted_rows'] ?></td>
            <td><span class="badge bg-mt"><?= htmlspecialchars($row['status']) ?></span></td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  <?php endif; ?>
</div>

<script>
const fileInput = document.getElementById('csvFile');
const dropZone = document.getElementById('csvDropZone');
const fileDropText = document.getElementById('fileDropText');

function setCsvFile(file) {
  if (!file) return;
  if (!file.name.toLowerCase().endsWith('.csv')) {
    alert('Lütfen yalnızca .csv dosyası seçin.');
    return;
  }
  const dt = new DataTransfer();
  dt.items.add(file);
  fileInput.files = dt.files;
  fileDropText.textContent = file.name;
}

dropZone?.addEventListener('click', () => fileInput.click());
dropZone?.addEventListener('keydown', (e) => {
  if (e.key === 'Enter' || e.key === ' ') {
    e.preventDefault();
    fileInput.click();
  }
});
fileInput?.addEventListener('change', function(){
  const name = this.files && this.files.length ? this.files[0].name : 'Dosya seçmek için tıklayın veya CSV’yi buraya sürükleyip bırakın';
  fileDropText.textContent = name;
});
['dragenter','dragover'].forEach(evt => {
  dropZone?.addEventListener(evt, (e) => {
    e.preventDefault();
    e.stopPropagation();
    dropZone.classList.add('dragover');
  });
});
['dragleave','drop'].forEach(evt => {
  dropZone?.addEventListener(evt, (e) => {
    e.preventDefault();
    e.stopPropagation();
    dropZone.classList.remove('dragover');
  });
});
dropZone?.addEventListener('drop', (e) => {
  const file = e.dataTransfer?.files?.[0];
  setCsvFile(file);
});
</script>

<?php include __DIR__ . '/includes/layout_end.php'; ?>
