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

$error = '';
$success = '';

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 tag name
            $checkStmt = $pdo->prepare("SELECT COUNT(*) FROM tags WHERE name = ?");
            $checkStmt->execute([$name]);
            if ($checkStmt->fetchColumn() > 0) {
                $error = 'This tag name already exists.';
            } else {
                // Insert new tag
                $insertStmt = $pdo->prepare("INSERT INTO tags (name, color) VALUES (?, ?)");
                $insertStmt->execute([$name, $color]);
                $success = 'Tag created successfully!';
                // Clear inputs after success
                $name = '';
                $color = '#cccccc';
            }
        } catch (PDOException $e) {
            $error = 'Database error: ' . htmlspecialchars($e->getMessage());
        }
    }
} else {
    $name = '';
    $color = '#cccccc';
}
?>

<h1>Create 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($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($color) ?>">
  </div>

  <button type="submit" class="btn btn-success">Create Tag</button>
</form>
