<?php
require_once '../../includes/config.php';

// Check if admin is logged in
if (!isAdminLoggedIn()) {
    redirect(SITE_URL . 'admin/login.php');
}

$pageTitle = "Tambah Kategori";

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = sanitize($_POST['name']);
    $description = sanitize($_POST['description']);
    
    // Validate input
    $errors = [];
    
    if (empty($name)) {
        $errors[] = "Nama kategori tidak boleh kosong";
    }
    
    // If no errors, insert the category
    if (empty($errors)) {
        try {
            $conn = connectDB();
            
            $stmt = $conn->prepare("INSERT INTO categories (name, description) VALUES (:name, :description)");
            $stmt->bindParam(':name', $name);
            $stmt->bindParam(':description', $description);
            $stmt->execute();
            
            $success = "Kategori berhasil ditambahkan";
            
            // Redirect back to categories list after successful addition
            redirect(SITE_URL . 'admin/categories/index.php?success=added');
            
        } catch (PDOException $e) {
            $error = "Error: " . $e->getMessage();
        }
    }
}

include '../header.php';
?>

<div class="admin-header">
    <h1>Tambah Kategori</h1>
    <div>
        <a href="index.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Kembali</a>
    </div>
</div>

<?php if (isset($success)): ?>
    <div class="success"><?php echo $success; ?></div>
<?php endif; ?>

<?php if (isset($error)): ?>
    <div class="error"><?php echo $error; ?></div>
<?php endif; ?>

<?php if (!empty($errors)): ?>
    <div class="error">
        <ul>
            <?php foreach ($errors as $err): ?>
                <li><?php echo $err; ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<div class="admin-content-box">
    <form action="add.php" method="post" class="admin-form">
        <div class="form-group">
            <label for="name">Nama Kategori <span class="required">*</span></label>
            <input type="text" id="name" name="name" value="<?php echo $name ?? ''; ?>" required>
        </div>
        
        <div class="form-group">
            <label for="description">Deskripsi</label>
            <textarea id="description" name="description" rows="5"><?php echo $description ?? ''; ?></textarea>
            <small>Deskripsi singkat untuk kategori ini (opsional)</small>
        </div>
        
        <div class="form-actions">
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Simpan Kategori</button>
            <a href="index.php" class="btn btn-secondary">Batal</a>
        </div>
    </form>
</div>

<?php include '../footer.php'; ?> 