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

if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') {
    header("Location: login.php?role=admin");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: add_product.php");
    exit();
}

$name = trim($_POST['name'] ?? '');
$description = trim($_POST['description'] ?? '');
$price = $_POST['price'] ?? 0;
$stock = $_POST['stock'] ?? 0;

$image = '';
if (isset($_FILES['image']) && $_FILES['image']['error'] == UPLOAD_ERR_OK) {
    $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
    $image = 'product_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
    move_uploaded_file($_FILES['image']['tmp_name'], __DIR__ . '/../uploads/' . $image);
}

$stmt = $pdo->prepare("INSERT INTO products (name, description, price, stock, image) VALUES (?,?,?,?,?)");
$stmt->execute([$name, $description, $price, $stock, $image]);

header("Location: products.php");
exit();
