<?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;

// Retrieve image_path from POST data. It's okay if it's null or empty.
$imagePath = $_POST['image_path'] ?? null; 

// New fields for product table
$stock = isset($_POST['stock']) ? (int)$_POST['stock'] : 0; // Default to 0 if not set or invalid

// Get admin_id from session. Ensure 'admin_id' is set during admin login.
if (!isset($_SESSION['admin_id'])) {
    // This is a critical error, admin actions should not proceed without admin_id
    $_SESSION['product_error_message'] = 'Admin session error. Please log in again.';
    header("Location: " . $redirect_url);
    exit();
}
$admin_id = (int)$_SESSION['admin_id'];

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'add' && !empty($name) && $price !== null && !empty($description) && isset($_POST['stock'])) {
        if ($userModel->addProduct($name, $price, $description, $stock, $admin_id, $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) && isset($_POST['stock'])) {
        if ($userModel->updateProduct($id, $name, $price, $description, $stock, $admin_id, $imagePath)) {
            $_SESSION['product_success_message'] = 'Product updated successfully.';
        } else {
            $_SESSION['product_error_message'] = 'Failed to update product.';
        }
    } else {
        $_SESSION['product_error_message'] = 'Invalid data (ensure name, price, description, stock are provided) or action for product operation.';
    }
} else {
    $_SESSION['product_error_message'] = 'Invalid request method.';
}

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