<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/auth.php';

requireAdmin();
$db = getDBConnection();

// Delete size
if (isset($_GET['action']) && $_GET['action'] === 'delete') {
    $id = (int)$_GET['id'];
    $stmt = $db->prepare("DELETE FROM sizes WHERE id = ?");
    $stmt->execute([$id]);
    $_SESSION['flash_success'] = 'ลบไซซ์เรียบร้อยแล้ว';
    header('Location: sizes.php');
    exit;
}

// Add/Edit size
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCSRFToken($_POST['csrf_token'] ?? '');
    $sizeId = (int)($_POST['size_id'] ?? 0);
    $name = sanitize($_POST['name'] ?? '');
    $sort_order = (int)($_POST['sort_order'] ?? 0);
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    
    if (!empty($name)) {
        if ($sizeId > 0) {
            $stmt = $db->prepare("UPDATE sizes SET name = ?, sort_order = ?, is_active = ? WHERE id = ?");
            $stmt->execute([$name, $sort_order, $is_active, $sizeId]);
            $_SESSION['flash_success'] = 'แก้ไขไซซ์เรียบร้อยแล้ว';
        } else {
            $stmt = $db->prepare("INSERT INTO sizes (name, sort_order, is_active) VALUES (?, ?, ?)");
            $stmt->execute([$name, $sort_order, $is_active]);
            $_SESSION['flash_success'] = 'เพิ่มไซซ์ใหม่เรียบร้อยแล้ว';
        }
        header('Location: sizes.php');
        exit;
    }
}

$sizes = $db->query("SELECT * FROM sizes ORDER BY sort_order ASC, id ASC")->fetchAll();

require_once __DIR__ . '/../../includes/admin_header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <h3 class="fw-bold mb-0">📏 จัดการไซซ์ (Size)</h3>
  <button class="btn btn-primary-custom rounded-pill" data-bs-toggle="modal" data-bs-target="#sizeModal" onclick="resetSizeForm()">+ เพิ่มไซซ์ใหม่</button>
</div>

<div class="card card-custom p-4">
  <table class="table table-hover align-middle">
    <thead>
      <tr>
        <th>ID</th>
        <th>ชื่อไซซ์</th>
        <th>ลำดับการแสดงผล</th>
        <th>สถานะ</th>
        <th>จัดการ</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($sizes as $s): ?>
        <tr>
          <td><?php echo $s['id']; ?></td>
          <td class="fw-bold"><span class="badge bg-dark px-3 py-2"><?php echo sanitize($s['name']); ?></span></td>
          <td><?php echo $s['sort_order']; ?></td>
          <td>
            <?php if ($s['is_active']): ?>
                <span class="badge bg-success">เปิดใช้งาน</span>
            <?php else: ?>
                <span class="badge bg-secondary">ปิดใช้งาน</span>
            <?php endif; ?>
          </td>
          <td>
            <button class="btn btn-sm btn-edit-custom rounded-pill me-1" onclick='editSize(<?php echo json_encode($s); ?>)'>✏️ แก้ไข</button>
            <a href="sizes.php?action=delete&id=<?php echo $s['id']; ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('ยืนยันการลบไซซ์นี้?')">🗑️ ลบ</a>
          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>

<!-- Modal Size Form -->
<div class="modal fade" id="sizeModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <form method="POST" action="">
        <div class="modal-header">
          <h5 class="modal-title fw-bold" id="sizeModalTitle">เพิ่มไซซ์ใหม่</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
          <input type="hidden" name="size_id" id="size_id">

          <div class="mb-3">
            <label class="form-label">ชื่อไซซ์ *</label>
            <input type="text" name="name" id="size_name" class="form-control" required placeholder="เช่น S, M, XL, Free Size">
          </div>
          
          <div class="mb-3">
            <label class="form-label">ลำดับการแสดงผล (น้อยไปมาก)</label>
            <input type="number" name="sort_order" id="size_sort" class="form-control" value="0">
          </div>

          <div class="form-check form-switch mb-3">
            <input class="form-check-input" type="checkbox" name="is_active" id="size_active" checked>
            <label class="form-check-label" for="size_active">เปิดใช้งาน</label>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary rounded-pill" data-bs-dismiss="modal">ยกเลิก</button>
          <button type="submit" class="btn btn-primary-custom rounded-pill">บันทึกไซซ์ ✨</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
function resetSizeForm() {
    document.getElementById('sizeModalTitle').innerText = 'เพิ่มไซซ์ใหม่';
    document.getElementById('size_id').value = '';
    document.getElementById('size_name').value = '';
    document.getElementById('size_sort').value = '0';
    document.getElementById('size_active').checked = true;
}

function editSize(s) {
    document.getElementById('sizeModalTitle').innerText = 'แก้ไขไซซ์';
    document.getElementById('size_id').value = s.id;
    document.getElementById('size_name').value = s.name;
    document.getElementById('size_sort').value = s.sort_order;
    document.getElementById('size_active').checked = s.is_active == 1;
    new bootstrap.Modal(document.getElementById('sizeModal')).show();
}
</script>

<?php require_once __DIR__ . '/../../includes/admin_footer.php'; ?>
