<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'Admin') {
    header("Location: ../view/user/index.php"); 
    exit();
}

require_once '../model/users.php'; // Contains User class

$userModel = new User();

$action = $_POST['action'] ?? null;
$name = $_POST['name'] ?? null;
$price = isset($_POST['price']) ? (float)$_POST['price'] : null;
$description = $_POST['description'] ?? null;
$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
$imagePath = $_POST['imagePath'] ?? null;

$redirect_url = '../view/admin/manage_products.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'add' && !empty($name) && $price !== null && !empty($description)) {
        if ($userModel->addProduct($name, $price, $description, $imagePath)) {
            $_SESSION['product_success_message'] = 'Product added successfully.';
        } else {
            $_SESSION['product_error_message'] = 'Failed to add product.';
        }
    } elseif ($action === 'edit' && $id > 0 && !empty($name) && $price !== null && !empty($description)) {
        if ($userModel->updateProduct($id, $name, $price, $description, $imagePath)) {
            $_SESSION['product_success_message'] = 'Product updated successfully.';
        } else {
            $_SESSION['product_error_message'] = 'Failed to update product.';
        }
    } else {
        $_SESSION['product_error_message'] = 'Invalid data or action for product operation.';
    }
} else {
    $_SESSION['product_error_message'] = 'Invalid request method.';
}

$userModel->closeConnection();
header("Location: " . $redirect_url);
exit();
?>