<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/layout.php';

$error = '';
$success = '';
$tag = null;

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
    die('Invalid tag ID.');
}

// Fetch the tag by ID
try {
    $stmt = $pdo->prepare("SELECT * FROM tags WHERE id = ?");
    $stmt->execute([$id]);
    $tag = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$tag) {
        die('Tag not found.');
    }
} catch (PDOException $e) {
    die("Database error: " . htmlspecialchars($e->getMessage()));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $color = trim($_POST['color'] ?? '');

    // Validate inputs
    if ($name === '' || $color === '') {
        $error = 'Please fill in all required fields.';
    } elseif (!preg_match('/^#[0-9A-Fa-f]{6}$/', $color)) {
        $error = 'Color must be a valid hex code like #ff0000.';
    } else {
        try {
            // Check for duplicate name on different ID
            $checkStmt = $pdo->prepare("SELECT COUNT(*) FROM tags WHERE name = ? AND id != ?");
            $checkStmt->execute([$name, $id]);
            if ($checkStmt->fetchColumn() > 0) {
                $error = 'This tag name is already in use.';
            } else {
                // Update the tag
                $updateStmt = $pdo->prepare("UPDATE tags SET name = ?, color = ? WHERE id = ?");
                $updateStmt->execute([$name, $color, $id]);
                $success = 'Tag updated successfully!';
                $tag['name'] = $name;
                $tag['color'] = $color;
            }
        } catch (PDOException $e) {
            $error = 'Database error: ' . htmlspecialchars($e->getMessage());
        }
    }
}
?>

<h1>Edit Tag</h1>

<?php if ($error): ?>
  <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>

<?php if ($success): ?>
  <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
<?php endif; ?>

<form method="post" id="tagForm">
  <div class="mb-3">
    <label for="name" class="form-label">Tag Name *</label>
    <input type="text" id="name" name="name" class="form-control" required value="<?= htmlspecialchars($tag['name'] ?? '') ?>">
  </div>

  <div class="mb-3">
    <label for="color" class="form-label">Color (Hex Code, e.g. #ff0000) *</label>
    <input type="color" id="color" name="color" class="form-control form-control-color" required value="<?= htmlspecialchars($tag['color'] ?? '#cccccc') ?>">
  </div>

  <button type="submit" class="btn btn-primary">Update Tag</button>
</form>
