<?php
session_start();
include 'config.php';

if(!isset($_SESSION['admin_id'])){
    header("Location: login.php");
    exit;
}

$msg = "";

if(isset($_POST['add_product'])){
    $name = $_POST['name'];
    $description = $_POST['description'];
    $price = $_POST['price'];

    if(isset($_FILES['image']) && $_FILES['image']['error'] == 0){
        $imageData = file_get_contents($_FILES['image']['tmp_name']);

        $stmt = $conn->prepare("INSERT INTO product (name, description, price, image, created_at) VALUES (?, ?, ?, ?, NOW())");
        $stmt->bind_param("ssds", $name, $description, $price, $imageData);

        if($stmt->execute()){
            $msg = "Product added successfully!";
        } else {
            $msg = "Error adding product.";
        }
        $stmt->close();
    } else {
        $msg = "Please select an image!";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Add Product</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="p-5">
<h2>Add New Product</h2>
<p><?= $msg ?></p>
<form method="post" enctype="multipart/form-data">
    <input type="text" name="name" placeholder="Product Name" class="form-control mb-2" required>
    <textarea name="description" placeholder="Description" class="form-control mb-2" required></textarea>
    <input type="number" step="0.01" name="price" placeholder="Price" class="form-control mb-2" required>
    <input type="file" name="image" class="form-control mb-2" accept="image/*" required>
    <button type="submit" name="add_product" class="btn btn-primary">Add Product</button>
    <a href="admin_dashboard.php" name="add_product" class="btn btn-primary">Go to Dashboard</a>
</form>
</body>
</html>
