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

$error = '';
$success = '';
$editing_color = null;

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

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

    if (empty($name) || empty($hex)) {
        $error = 'Both Color Name and HEX Code are required.';
    } else {
        // Simple hex format check
        if (!preg_match('/^#[a-fA-F0-9]{6}$/', $hex)) {
            $error = 'Invalid HEX code format. Must be like #FFFFFF.';
        } else {
            try {
                if ($action === 'edit' && $color_id > 0) {
                    // Update existing color
                    $stmt_update = $pdo->prepare("UPDATE colors SET name = ?, hex = ?, border = ? WHERE id = ?");
                    $stmt_update->execute([$name, $hex, $border, $color_id]);
                    $success = 'Color swatch updated successfully!';
                    echo "<script>setTimeout(() => { window.location.href = 'colors.php'; }, 1000);</script>";
                } else {
                    // Add new color
                    // Check duplicate name
                    $stmt_check = $pdo->prepare("SELECT COUNT(*) FROM colors WHERE name = ?");
                    $stmt_check->execute([$name]);
                    if ($stmt_check->fetchColumn() > 0) {
                        $error = 'A color swatch with this name already exists.';
                    } else {
                        $stmt_insert = $pdo->prepare("INSERT INTO colors (name, hex, border) VALUES (?, ?, ?)");
                        $stmt_insert->execute([$name, $hex, $border]);
                        $success = 'New color swatch introduced successfully!';
                        echo "<script>setTimeout(() => { window.location.href = 'colors.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 colors WHERE id = ?");
        $stmt_edit->execute([$edit_id]);
        $editing_color = $stmt_edit->fetch();
    } catch (Exception $e) {
        $error = 'Failed to load color for editing.';
    }
}

// Fetch all colors
$colors = [];
try {
    $colors = $pdo->query("SELECT * FROM colors ORDER BY name ASC")->fetchAll();
} catch (Exception $e) {
    $error = 'Failed to retrieve catalog colors: ' . $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">Colors</li>
            </ol>
        </nav>
        <h2 class="text-white">Couture Colors Management</h2>
        <p class="text-muted small">Design, add, and refine the luxury color palettes available for your masterworks catalog.</p>
    </div>
</div>

<div class="row g-4">
    <!-- Left Column: List of colors -->
    <div class="col-lg-7">
        <div class="admin-card h-100">
            <h4 class="text-white mb-4"><i class="fa-solid fa-palette text-warning me-2"></i> Active Color Swatches</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($colors)): ?>
                <div class="text-center py-5 text-muted">
                    <i class="fa-solid fa-droplet-slash display-4 mb-3 d-block opacity-25"></i>
                    No color palettes have been defined.
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-dark table-luxury">
                        <thead>
                            <tr>
                                <th style="width: 80px;">Swatch</th>
                                <th>Color Name</th>
                                <th>HEX Code</th>
                                <th>Border Color</th>
                                <th class="text-end" style="width: 150px;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($colors as $color): ?>
                                <tr>
                                    <td>
                                        <div class="rounded-circle" style="width: 32px; height: 32px; background-color: <?php echo $color['hex']; ?>; border: 2px solid <?php echo $color['border']; ?>; box-shadow: 0 4px 8px rgba(0,0,0,0.3);" title="<?php echo htmlspecialchars($color['name']); ?>"></div>
                                    </td>
                                    <td><strong class="text-white"><?php echo htmlspecialchars($color['name']); ?></strong></td>
                                    <td><code class="text-warning bg-dark px-2 py-1 rounded" style="font-size: 0.8rem;"><?php echo htmlspecialchars($color['hex']); ?></code></td>
                                    <td><code class="text-muted bg-dark px-2 py-1 rounded" style="font-size: 0.8rem;"><?php echo htmlspecialchars($color['border']); ?></code></td>
                                    <td class="text-end">
                                        <div class="d-flex gap-2 justify-content-end">
                                            <a href="colors.php?edit=<?php echo $color['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="colors.php?delete=<?php echo $color['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 color \'<?php echo htmlspecialchars($color['name']); ?>\'? All product associations will be permanently removed.');">
                                                <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_color): ?>
                    <i class="fa-solid fa-pen-nib text-warning me-2"></i> Refine Swatch Details
                <?php else: ?>
                    <i class="fa-solid fa-plus-circle text-warning me-2"></i> Add New Color Swatch
                <?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="colors.php" method="POST">
                <input type="hidden" name="action" value="<?php echo $editing_color ? 'edit' : 'add'; ?>">
                <?php if ($editing_color): ?>
                    <input type="hidden" name="color_id" value="<?php echo $editing_color['id']; ?>">
                <?php endif; ?>

                <div class="mb-3">
                    <label for="name" class="form-label text-muted small text-uppercase fw-bold">Color Name *</label>
                    <input type="text" class="form-control" id="name" name="name" required placeholder="e.g. Midnight Black" value="<?php echo $editing_color ? htmlspecialchars($editing_color['name']) : ''; ?>">
                    <div class="form-text text-muted" style="font-size: 0.7rem;">Choose a premium fashion name.</div>
                </div>

                <div class="mb-3">
                    <label for="hex" class="form-label text-muted small text-uppercase fw-bold">HEX Color Code *</label>
                    <div class="d-flex gap-2">
                        <input type="color" class="form-control-color border-secondary bg-dark rounded" style="width: 45px; height: 38px; cursor: pointer; padding: 2px;" id="hex_picker" value="<?php echo $editing_color ? htmlspecialchars($editing_color['hex']) : '#000000'; ?>" onchange="syncHexValue(this.value, 'hex')">
                        <input type="text" class="form-control flex-grow-1" id="hex" name="hex" required placeholder="#FFFFFF" value="<?php echo $editing_color ? htmlspecialchars($editing_color['hex']) : '#000000'; ?>" onkeyup="syncColorPicker(this.value, 'hex_picker')">
                    </div>
                    <div class="form-text text-muted" style="font-size: 0.7rem;">Enter hex code or use the color picker swatch on the left.</div>
                </div>

                <div class="mb-4">
                    <label for="border" class="form-label text-muted small text-uppercase fw-bold">Swatch Border Color</label>
                    <div class="d-flex gap-2">
                        <input type="color" class="form-control-color border-secondary bg-dark rounded" style="width: 45px; height: 38px; cursor: pointer; padding: 2px;" id="border_picker" value="<?php echo $editing_color ? htmlspecialchars($editing_color['border']) : '#FFFFFF'; ?>" onchange="syncHexValue(this.value, 'border')">
                        <input type="text" class="form-control flex-grow-1" id="border" name="border" placeholder="#FFFFFF" value="<?php echo $editing_color ? htmlspecialchars($editing_color['border']) : '#FFFFFF'; ?>" onkeyup="syncColorPicker(this.value, 'border_picker')">
                    </div>
                    <div class="form-text text-muted" style="font-size: 0.7rem;">Required to guarantee swatch visibility on black backgrounds (e.g. white/gray swatches).</div>
                </div>

                <div class="d-flex gap-2 justify-content-end mt-4 border-top border-dark pt-3">
                    <?php if ($editing_color): ?>
                        <a href="colors.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_color ? 'Apply Swatch Changes <i class="fa-solid fa-check-double ms-2"></i>' : 'Introduce Swatch <i class="fa-solid fa-cloud-arrow-up ms-2"></i>'; ?>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function syncHexValue(val, targetId) {
    document.getElementById(targetId).value = val.toUpperCase();
}

function syncColorPicker(val, pickerId) {
    if (val.match(/^#[a-fA-F0-9]{6}$/)) {
        document.getElementById(pickerId).value = val;
    }
}
</script>

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