<?php
include "../db.php";  // PDO connection

$statusMsg = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $category_name = trim($_POST['category_name']);

    $image = $_FILES['image']['name'];
    $clean_name = str_replace(' ', '-', $image);
    $filename = time() . "_" . $clean_name;

    $upload_dir = "../lbfood/uploads/categories/";
    $db_path = $filename;

    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }

    $target_path = $upload_dir . $filename;

    if (move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {

        $stmt = $pdo->prepare("
            INSERT INTO categories (category_name, image_path, created_at)
            VALUES (:category_name, :image_path, NOW())
        ");

        $stmt->execute([
            ':category_name' => $category_name,
            ':image_path'    => $db_path
        ]);

        $statusMsg = "<div class='alert ok'>Category added successfully!</div>";

    } else {
        $statusMsg = "<div class='alert error'>Failed to upload image.</div>";
    }
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Add Category</title>
<meta name="viewport" content="width=device-width,initial-scale=1">

<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap" rel="stylesheet">

<style>
:root{
    --primary:#0b4f27;
    --primary-dark:#083a1d;
    --bg:#f3f4f6;
    --card:#ffffff;
    --text:#1f2937;
    --muted:#6b7280;
}

body{
    font-family:'Poppins',sans-serif;
    background:var(--bg);
    color:var(--text);
    padding:20px;
}

.container{
    max-width:500px;
    margin:auto;
}

.card{
    background:var(--card);
    padding:25px;
    border-radius:14px;
    box-shadow:0 8px 20px rgba(0,0,0,.06);
}

h2{
    text-align:center;
    color:var(--primary);
    margin-bottom:20px;
}

label{
    font-weight:500;
    margin-bottom:6px;
    display:block;
}

input[type="text"],
input[type="file"]{
    width:100%;
    padding:10px 12px;
    border-radius:8px;
    border:1px solid #d1d5db;
    margin-bottom:15px;
    font-size:14px;
}

button{
    width:100%;
    background:var(--primary);
    color:#fff;
    border:none;
    padding:11px;
    font-size:15px;
    border-radius:8px;
    cursor:pointer;
    font-weight:600;
}

button:hover{
    background:var(--primary-dark);
}

.alert{
    padding:12px;
    border-radius:8px;
    margin-bottom:15px;
    font-weight:500;
    text-align:center;
}

.alert.ok{
    background:#dcfce7;
    color:#065f46;
}

.alert.error{
    background:#fee2e2;
    color:#7f1d1d;
}
</style>
</head>

<body>

<div class="container">
<div class="card">

<h2>Add New Category</h2>

<?= $statusMsg; ?>

<form method="POST" enctype="multipart/form-data">

    <label>Category Name</label>
    <input type="text" name="category_name" required>

    <label>Category Image</label>
    <input type="file" name="image" required>

    <button type="submit">Add Category</button>

</form>

</div>
</div>

</body>
</html>
