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

if (is_post()) {
    verify_csrf();

    $action = $_POST['action'] ?? '';

    if ($action === 'create') {
        $code = strtoupper(trim((string)($_POST['store_code'] ?? '')));
        $name = trim((string)($_POST['store_name'] ?? ''));

        if ($code === '' || $name === '') {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'Mağaza kodu ve adı zorunlu.'];
        } else {
            try {
                $stmt = db()->prepare("INSERT INTO stores (store_code, store_name, is_active) VALUES (:code, :name, 1)");
                $stmt->execute(['code' => $code, 'name' => $name]);
                $_SESSION['flash'] = ['type' => 'success', 'msg' => 'Mağaza eklendi.'];
            } catch (Throwable $e) {
                $_SESSION['flash'] = ['type' => 'error', 'msg' => 'Mağaza eklenemedi: ' . $e->getMessage()];
            }
        }
        redirect('stores.php');
    }

    if ($action === 'update') {
        $id = (int)($_POST['id'] ?? 0);
        $code = strtoupper(trim((string)($_POST['store_code'] ?? '')));
        $name = trim((string)($_POST['store_name'] ?? ''));
        $active = isset($_POST['is_active']) ? 1 : 0;

        if ($id <= 0 || $code === '' || $name === '') {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'Eksik bilgi.'];
        } else {
            try {
                $stmt = db()->prepare("UPDATE stores SET store_code = :code, store_name = :name, is_active = :active WHERE id = :id");
                $stmt->execute(['code' => $code, 'name' => $name, 'active' => $active, 'id' => $id]);
                $_SESSION['flash'] = ['type' => 'success', 'msg' => 'Mağaza güncellendi.'];
            } catch (Throwable $e) {
                $_SESSION['flash'] = ['type' => 'error', 'msg' => 'Mağaza güncellenemedi: ' . $e->getMessage()];
            }
        }
        redirect('stores.php');
    }
}

$stores = db()->query("SELECT * FROM stores ORDER BY is_active DESC, store_code")->fetchAll();

$page_title = 'Mağazalar';
$active_menu = 'stores';
include __DIR__ . '/includes/layout.php';
?>

<div class="ph">
  <div>
    <h1>Mağazalar</h1>
    <p>CSV upload, dashboard ve kullanıcı mağaza bağlantıları bu tablodan beslenir.</p>
  </div>
</div>

<div class="grid-auto">
  <div class="card">
    <div class="card-header"><span class="card-title">Yeni Mağaza Ekle</span></div>
    <div class="card-body">
      <form method="post">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="create">
        <div class="form-group">
          <label class="form-label">Mağaza Kodu</label>
          <input type="text" name="store_code" class="form-control" placeholder="BLG, VOQ, NEW" required>
          <div class="form-hint">Büyük harf, kısa kod. Örn: BLG, LUW, VOQ.</div>
        </div>
        <div class="form-group">
          <label class="form-label">Mağaza Adı</label>
          <input type="text" name="store_name" class="form-control" placeholder="BLG Jewels" required>
        </div>
        <button type="submit" class="btn btn-primary">Mağaza Ekle</button>
      </form>
    </div>
  </div>

  <div class="card">
    <div class="card-header"><span class="card-title">Not</span></div>
    <div class="card-body">
      <div class="alert alert-info">
        <span class="alert-ico">ℹ</span>
        <div>
          Yeni mağaza eklenince CSV yükleme ekranındaki mağaza listesine otomatik gelir.
          Ürün eşleşmesi mağaza sayısına göre değil, <strong>product_store_skus</strong> tablosundaki SKU’ya göre yapılır.
        </div>
      </div>
    </div>
  </div>
</div>

<div class="card">
  <div class="card-header"><span class="card-title">Mevcut Mağazalar</span></div>
  <div class="card-body">
    <div class="store-edit-row hide-sm" style="font-weight:700;color:var(--text-muted);font-size:11px;text-transform:uppercase">
      <div>ID</div><div>Kod</div><div>Ad</div><div>Aktif</div><div>İşlem</div>
    </div>
    <?php foreach ($stores as $store): ?>
      <form method="post" class="store-edit-row">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="update">
        <input type="hidden" name="id" value="<?= (int)$store['id'] ?>">
        <div class="mn c-mt">#<?= (int)$store['id'] ?></div>
        <div><input type="text" name="store_code" class="form-control" value="<?= htmlspecialchars($store['store_code']) ?>" required></div>
        <div><input type="text" name="store_name" class="form-control" value="<?= htmlspecialchars($store['store_name']) ?>" required></div>
        <label class="fc gap8"><input type="checkbox" name="is_active" value="1" <?= (int)$store['is_active'] === 1 ? 'checked' : '' ?>> Aktif</label>
        <div><button type="submit" class="btn btn-secondary btn-sm">Kaydet</button></div>
      </form>
    <?php endforeach; ?>
  </div>
</div>

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