<?php
require_once __DIR__ . '/header.php';

// บังคับสิทธิ์ Admin เท่านั้น
if (!is_admin()) {
    header('Location: index.php');
    exit;
}

$message = '';
$message_type = '';

// ------------------------------------------------------------
// จัดการฟอร์มเพิ่ม / แก้ไข / ลบ สินค้า
// ------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];

    // ฟังก์ชันช่วยจัดการอัปโหลดไฟล์รูปภาพ
    $handle_image_upload = function($file_key, $default = 'default.jpg') {
        if (isset($_FILES[$file_key]) && $_FILES[$file_key]['error'] === UPLOAD_ERR_OK) {
            $ext = strtolower(pathinfo($_FILES[$file_key]['name'], PATHINFO_EXTENSION));
            $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'];
            if (in_array($ext, $allowed)) {
                $new_filename = 'prod_' . time() . '_' . rand(1000, 9999) . '.' . $ext;
                $target_dir = __DIR__ . '/assets/images/';
                if (!is_dir($target_dir)) {
                    mkdir($target_dir, 0777, true);
                }
                if (move_uploaded_file($_FILES[$file_key]['tmp_name'], $target_dir . $new_filename)) {
                    return $new_filename;
                }
            }
        }
        return null;
    };

    // 1. เพิ่มสินค้าใหม่
    if ($action === 'add') {
        $name        = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $price       = filter_input(INPUT_POST, 'price', FILTER_VALIDATE_FLOAT);
        $stock       = filter_input(INPUT_POST, 'stock', FILTER_VALIDATE_INT);
        
        $uploaded_image = $handle_image_upload('image_file');
        $image = $uploaded_image ?: trim($_POST['image'] ?? 'default.jpg');
        if (empty($image)) $image = 'default.jpg';

        if ($name && $price !== false && $stock !== false) {
            $stmt = $pdo->prepare("INSERT INTO products (name, description, price, stock, image) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$name, $description, $price, $stock, $image]);
            $message = "เพิ่มสินค้าใหม่ <strong>" . htmlspecialchars($name) . "</strong> สำเร็จ!";
            $message_type = "success";
        } else {
            $message = "กรุณากรอกข้อมูลสินค้าให้ถูกต้องครบถ้วน";
            $message_type = "danger";
        }
    }

    // 2. แก้ไขสินค้า
    if ($action === 'edit') {
        $id          = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT);
        $name        = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $price       = filter_input(INPUT_POST, 'price', FILTER_VALIDATE_FLOAT);
        $stock       = filter_input(INPUT_POST, 'stock', FILTER_VALIDATE_INT);

        $uploaded_image = $handle_image_upload('image_file');
        $image = $uploaded_image ?: trim($_POST['image'] ?? 'default.jpg');

        if ($id && $name && $price !== false && $stock !== false) {
            $stmt = $pdo->prepare("UPDATE products SET name = ?, description = ?, price = ?, stock = ?, image = ? WHERE id = ?");
            $stmt->execute([$name, $description, $price, $stock, $image, $id]);
            $message = "อัปเดตข้อมูลสินค้าเรียบร้อยแล้ว!";
            $message_type = "success";
        }
    }

    // 3. ลบสินค้า
    if ($action === 'delete') {
        $id = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT);
        if ($id) {
            $stmt = $pdo->prepare("DELETE FROM products WHERE id = ?");
            $stmt->execute([$id]);
            $message = "ลบสินค้าออกจากระบบเรียบร้อยแล้ว";
            $message_type = "info";
        }
    }
}

// ดึงรายการสินค้าทั้งหมด
$products = $pdo->query("SELECT * FROM products ORDER BY id DESC")->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h3 class="fw-bold mb-1"><i class="fa-solid fa-box-archive text-primary me-2"></i>จัดการสินค้าในร้าน</h3>
        <p class="text-muted small mb-0">เพิ่ม แก้ไขราคาสินค้า ปรับเพิ่มสต็อก หรือลบรายการสินค้า</p>
    </div>
    <button class="btn btn-primary-custom rounded-pill px-4" data-bs-toggle="modal" data-bs-target="#addProductModal">
        <i class="fa-solid fa-plus me-1"></i> เพิ่มสินค้าใหม่
    </button>
</div>

<?php if (!empty($message)): ?>
    <div class="alert alert-<?= $message_type ?> alert-dismissible fade show rounded-3 mb-4" role="alert">
        <i class="fa-solid fa-info-circle me-2"></i> <?= $message ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<div class="card border-0 shadow-sm rounded-4 overflow-hidden">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table align-middle table-hover mb-0">
                <thead class="table-light">
                    <tr>
                        <th style="width: 80px;" class="ps-4">รูปภาพ</th>
                        <th>ชื่อสินค้า</th>
                        <th>ราคา</th>
                        <th>สต็อกคงเหลือ</th>
                        <th class="text-center" style="width: 150px;">การจัดการ</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($products)): ?>
                        <tr><td colspan="5" class="text-center py-4 text-muted">ยังไม่มีสินค้าในร้านค้า</td></tr>
                    <?php else: ?>
                        <?php foreach ($products as $p): ?>
                            <tr>
                                <td class="ps-4">
                                    <?php $img = get_product_image_url($p['image']); ?>
                                    <img src="<?= htmlspecialchars($img) ?>" class="rounded-3 border" style="width: 50px; height: 50px; object-fit: cover;" alt="">
                                </td>
                                <td>
                                    <h6 class="mb-0 fw-semibold text-dark"><?= htmlspecialchars($p['name']) ?></h6>
                                    <small class="text-muted"><?= htmlspecialchars(mb_strimwidth($p['description'], 0, 70, "...")) ?></small>
                                </td>
                                <td class="fw-bold text-primary"><?= format_price($p['price']) ?></td>
                                <td>
                                    <?php if ($p['stock'] > 5): ?>
                                        <span class="badge bg-success rounded-pill px-3 py-2"><?= $p['stock'] ?> ชิ้น</span>
                                    <?php else: ?>
                                        <span class="badge bg-danger rounded-pill px-3 py-2">เหลือน้อย: <?= $p['stock'] ?> ชิ้น</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center">
                                    <!-- ปุ่มแก้ไข (เปิดหน้าแก้ไขแบบเต็ม) -->
                                    <a href="product_edit.php?id=<?= $p['id'] ?>"
                                       class="btn btn-sm btn-outline-primary rounded-circle me-1"
                                       style="width: 32px; height: 32px; line-height: 1.5;"
                                       title="แก้ไขสินค้า (เพิ่มรูป ไซส์ รายละเอียด)">
                                        <i class="fa-solid fa-pen"></i>
                                    </a>

                                    <!-- ปุ่มลบ -->
                                    <form method="POST" action="admin_products.php" class="d-inline" onsubmit="return confirm('คุณต้องการลบสินค้านี้ใช่หรือไม่?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="product_id" value="<?= $p['id'] ?>">
                                        <button type="submit" class="btn btn-sm btn-outline-danger rounded-circle" style="width: 32px; height: 32px;" title="ลบ">
                                            <i class="fa-solid fa-trash-can"></i>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Modal เพิ่มสินค้าใหม่ -->
<div class="modal fade" id="addProductModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content rounded-4 border-0">
            <form method="POST" action="admin_products.php" enctype="multipart/form-data">
                <input type="hidden" name="action" value="add">
                
                <div class="modal-header bg-primary text-white rounded-top-4">
                    <h5 class="modal-title fw-bold"><i class="fa-solid fa-plus-circle me-2"></i>เพิ่มสินค้าใหม่สำหรับผู้ขาย</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-4">
                    <div class="mb-3">
                        <label class="form-label fw-medium">ชื่อสินค้า</label>
                        <input type="text" name="name" class="form-control" placeholder="เช่น หูฟังไร้สาย Bluetooth" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-medium">รายละเอียดสินค้า</label>
                        <textarea name="description" class="form-control" rows="3" placeholder="อธิบายคุณสมบัติสินค้า..."></textarea>
                    </div>
                    <div class="row g-2 mb-3">
                        <div class="col-6">
                            <label class="form-label fw-medium">ราคา (บาท)</label>
                            <input type="number" step="0.01" name="price" class="form-control" placeholder="1500.00" required>
                        </div>
                        <div class="col-6">
                            <label class="form-label fw-medium">จำนวนสต็อก</label>
                            <input type="number" name="stock" class="form-control" placeholder="10" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-medium"><i class="fa-solid fa-image text-primary me-1"></i>อัปโหลดไฟล์รูปภาพสินค้า</label>
                        <input type="file" name="image_file" class="form-control mb-2" accept="image/*">
                        <small class="text-muted d-block">หรือระบุชื่อไฟล์ที่มีอยู่แล้ว:</small>
                        <input type="text" name="image" class="form-control form-control-sm" placeholder="default.jpg" value="default.jpg">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light rounded-pill px-3" data-bs-dismiss="modal">ยกเลิก</button>
                    <button type="submit" class="btn btn-primary-custom rounded-pill px-4">บันทึกสินค้าใหม่</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/footer.php'; ?>
