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

$error = '';
$success = '';
$editing_size = null;

// Handle Delete Size Action
if (isset($_GET['delete'])) {
    $delete_id = intval($_GET['delete']);
    try {
        $stmt_del = $pdo->prepare("DELETE FROM sizes WHERE id = ?");
        $stmt_del->execute([$delete_id]);
        $success = 'Size tier removed successfully!';
        echo "<script>setTimeout(() => { window.location.href = 'sizes.php'; }, 1000);</script>";
    } catch (Exception $e) {
        $error = 'Failed to delete size: ' . $e->getMessage();
    }
}

// Handle Form Submission (Add or Edit)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $action = isset($_POST['action']) ? $_POST['action'] : 'add';
    $size_id = isset($_POST['size_id']) ? intval($_POST['size_id']) : 0;

    if (empty($name)) {
        $error = 'Size Name is required.';
    } else {
        try {
            if ($action === 'edit' && $size_id > 0) {
                // Update existing size
                $stmt_update = $pdo->prepare("UPDATE sizes SET name = ? WHERE id = ?");
                $stmt_update->execute([$name, $size_id]);
                $success = 'Size tier updated successfully!';
                echo "<script>setTimeout(() => { window.location.href = 'sizes.php'; }, 1000);</script>";
            } else {
                // Add new size
                // Check duplicate
                $stmt_check = $pdo->prepare("SELECT COUNT(*) FROM sizes WHERE name = ?");
                $stmt_check->execute([$name]);
                if ($stmt_check->fetchColumn() > 0) {
                    $error = 'A size tier with this name already exists.';
                } else {
                    $stmt_insert = $pdo->prepare("INSERT INTO sizes (name) VALUES (?)");
                    $stmt_insert->execute([$name]);
                    $success = 'New size tier introduced successfully!';
                    echo "<script>setTimeout(() => { window.location.href = 'sizes.php'; }, 1000);</script>";
                }
            }
        } catch (Exception $e) {
            $error = 'Database transaction failed: ' . $e->getMessage();
        }
    }
}

// Check if we are in Edit Mode
if (isset($_GET['edit'])) {
    $edit_id = intval($_GET['edit']);
    try {
        $stmt_edit = $pdo->prepare("SELECT * FROM sizes WHERE id = ?");
        $stmt_edit->execute([$edit_id]);
        $editing_size = $stmt_edit->fetch();
    } catch (Exception $e) {
        $error = 'Failed to load size for editing.';
    }
}

// Fetch all sizes
$sizes = [];
try {
    $sizes = $pdo->query("SELECT * FROM sizes ORDER BY id ASC")->fetchAll();
} catch (Exception $e) {
    $error = 'Failed to retrieve catalog sizes: ' . $e->getMessage();
}
?>

<div class="row mb-4">
    <div class="col-12">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                <li class="breadcrumb-item active" aria-current="page">Sizes</li>
            </ol>
        </nav>
        <h2 class="text-white">Couture Sizes Management</h2>
        <p class="text-muted small">Design, add, and refine the catalog sizes available for apparel, footwear, and accessory lines.</p>
    </div>
</div>

<div class="row g-4">
    <!-- Left Column: List of sizes -->
    <div class="col-lg-7">
        <div class="admin-card h-100">
            <h4 class="text-white mb-4"><i class="fa-solid fa-arrows-left-right text-warning me-2"></i> Active Size Tiers</h4>
            
            <?php if (!empty($error) && !isset($_POST['action'])): ?>
                <div class="alert alert-danger border-danger bg-dark text-danger rounded-3 py-2 px-3 small mb-4" role="alert">
                    <i class="fa-solid fa-circle-exclamation me-2"></i> <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>

            <?php if (!empty($success)): ?>
                <div class="alert alert-success border-success bg-dark text-success rounded-3 py-2 px-3 small mb-4" role="alert">
                    <i class="fa-solid fa-circle-check me-2"></i> <?php echo htmlspecialchars($success); ?>
                </div>
            <?php endif; ?>

            <?php if (empty($sizes)): ?>
                <div class="text-center py-5 text-muted">
                    <i class="fa-solid fa-arrows-up-down display-4 mb-3 d-block opacity-25"></i>
                    No size tiers have been defined.
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-dark table-luxury">
                        <thead>
                            <tr>
                                <th style="width: 80px;">ID</th>
                                <th>Size Name / Tag</th>
                                <th class="text-end" style="width: 150px;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($sizes as $size): ?>
                                <tr>
                                    <td><span class="text-muted small">#<?php echo $size['id']; ?></span></td>
                                    <td><strong class="text-white bg-dark px-3 py-2 border border-secondary rounded fw-bold fs-7"><?php echo htmlspecialchars($size['name']); ?></strong></td>
                                    <td class="text-end">
                                        <div class="d-flex gap-2 justify-content-end">
                                            <a href="sizes.php?edit=<?php echo $size['id']; ?>" class="btn btn-outline-warning btn-sm rounded-pill px-3" style="font-size: 0.7rem; font-weight: bold;">
                                                <i class="fa-solid fa-pen-to-square me-1"></i> Edit
                                            </a>
                                            <a href="sizes.php?delete=<?php echo $size['id']; ?>" class="btn btn-outline-danger btn-sm rounded-pill px-3" style="font-size: 0.7rem; font-weight: bold;" onclick="return confirm('Are you sure you want to delete the size tier \'<?php echo htmlspecialchars($size['name']); ?>\'? All product mappings will be deleted.');">
                                                <i class="fa-solid fa-trash-can me-1"></i> Delete
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Right Column: Add/Edit Form -->
    <div class="col-lg-5">
        <div class="admin-card">
            <h4 class="text-white mb-4">
                <?php if ($editing_size): ?>
                    <i class="fa-solid fa-pen-nib text-warning me-2"></i> Refine Size Tier Details
                <?php else: ?>
                    <i class="fa-solid fa-plus-circle text-warning me-2"></i> Add New Size Tier
                <?php endif; ?>
            </h4>

            <?php if (!empty($error) && isset($_POST['action'])): ?>
                <div class="alert alert-danger border-danger bg-dark text-danger rounded-3 py-2 px-3 small mb-4" role="alert">
                    <i class="fa-solid fa-circle-exclamation me-2"></i> <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>

            <form action="sizes.php" method="POST">
                <input type="hidden" name="action" value="<?php echo $editing_size ? 'edit' : 'add'; ?>">
                <?php if ($editing_size): ?>
                    <input type="hidden" name="size_id" value="<?php echo $editing_size['id']; ?>">
                <?php endif; ?>

                <div class="mb-4">
                    <label for="name" class="form-label text-muted small text-uppercase fw-bold">Size Name / Label *</label>
                    <input type="text" class="form-control" id="name" name="name" required placeholder="e.g. XXL, 42, Medium" value="<?php echo $editing_size ? htmlspecialchars($editing_size['name']) : ''; ?>">
                    <div class="form-text text-muted" style="font-size: 0.7rem;">Enter standard apparel codes (S, M, L) or numerical metrics.</div>
                </div>

                <div class="d-flex gap-2 justify-content-end mt-4 border-top border-dark pt-3">
                    <?php if ($editing_size): ?>
                        <a href="sizes.php" class="btn btn-outline-secondary rounded-pill px-4 py-2 text-uppercase tracking-wider fw-bold" style="font-size: 0.75rem; border-color: var(--border-gray);">
                            Cancel
                        </a>
                    <?php endif; ?>
                    <button type="submit" class="btn-luxury px-4 py-2">
                        <?php echo $editing_size ? 'Apply Size Changes <i class="fa-solid fa-check-double ms-2"></i>' : 'Introduce Size <i class="fa-solid fa-cloud-arrow-up ms-2"></i>'; ?>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

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