<?php
session_start();
include('shikanisha.kts.php');

header('Content-Type: application/json');
$response = ['success' => false, 'message' => ''];

// Validate request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response['message'] = 'Invalid request method.';
    echo json_encode($response);
    exit;
}

// Validate required fields
$requiredFields = ['name', 'type', 'price', 'category'];
foreach ($requiredFields as $field) {
    if (empty($_POST[$field])) {
        $response['message'] = "Missing required field: $field";
        echo json_encode($response);
        exit;
    }
}

// Sanitize input data
$name = trim($_POST['name']);
$type = trim($_POST['type']);
$description = trim($_POST['description'] ?? '');
$price = (float)$_POST['price'];
$category = trim($_POST['category']);
$cat = 'Food'; // Default category

if ($price <= 0) {
    $response['message'] = 'Price must be greater than 0';
    echo json_encode($response);
    exit;
}

// Handle image upload
$imagePath = null;
if (isset($_FILES['image'])) {
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    $maxSize = 2 * 1024 * 1024; // 2MB

    if ($_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $fileInfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($fileInfo, $_FILES['image']['tmp_name']);
        finfo_close($fileInfo);

        if (!in_array($mime, $allowedTypes)) {
            $response['message'] = 'Invalid image format. Only JPG, PNG, and GIF are allowed.';
            echo json_encode($response);
            exit;
        }

        if ($_FILES['image']['size'] > $maxSize) {
            $response['message'] = 'Image size exceeds maximum limit of 2MB';
            echo json_encode($response);
            exit;
        }

        $targetDir = "../uploads/";
        if (!file_exists($targetDir)) {
            mkdir($targetDir, 0755, true);
        }

        $extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $filename = uniqid('food_') . '.' . $extension;
        $targetFile = $targetDir . $filename;

        if (move_uploaded_file($_FILES["image"]["tmp_name"], $targetFile)) {
            $imagePath = $targetFile;
        } else {
            $response['message'] = 'Failed to upload image';
            echo json_encode($response);
            exit;
        }
    } elseif ($_FILES['image']['error'] !== UPLOAD_ERR_NO_FILE) {
        $response['message'] = 'Image upload error: ' . $_FILES['image']['error'];
        echo json_encode($response);
        exit;
    }
}

// Calculate total cost price
$totalCostPrice = 0;
if (!empty($_SESSION['recipe'])) {
    foreach ($_SESSION['recipe'] as $ingredient) {
        if (!isset($ingredient['cost'], $ingredient['quantity'])) {
            $response['message'] = 'Invalid recipe data structure';
            echo json_encode($response);
            exit;
        }
        $totalCostPrice += (float)$ingredient['cost'] * (float)$ingredient['quantity'];
    }
}

if (!empty($_SESSION['food_items'])) {
    foreach ($_SESSION['food_items'] as $item) {
        if (!isset($item['food_cost'], $item['quantity'])) {
            $response['message'] = 'Invalid food items data structure';
            echo json_encode($response);
            exit;
        }
        $totalCostPrice += (float)$item['food_cost'] * (float)$item['quantity'];
    }
}

// Start transaction
$conn->begin_transaction();

// Prepare statements
$stmt = $verifyStmt = $ingredientStmt = $groupStmt = null;

try {
    // Insert into food
    $stmt = $conn->prepare("INSERT INTO `food` (`name`, `price`, `food_group`, `image`, `description`, `cost_price`, `cat`, `category`)
        VALUES (?,  ?, ?, ?, ?, ?, ?, ?)");
    if (!$stmt) throw new Exception('Food insert prepare failed: ' . $conn->error);

    $stmt->bind_param("sdsssdss", $name,  $price, $type, $imagePath, $description, $totalCostPrice, $cat, $category);
    if (!$stmt->execute()) throw new Exception('Food insert execute failed: ' . $stmt->error);

    $food_id = $conn->insert_id;
    $stmt->close(); $stmt = null;

    // Process recipe ingredients
    if (!empty($_SESSION['recipe'])) {
        $verifyStmt = $conn->prepare("SELECT id FROM ingredients WHERE id = ?");
        if (!$verifyStmt) throw new Exception('Ingredient verification prepare failed: ' . $conn->error);

        $ingredientStmt = $conn->prepare("INSERT INTO `food_ingredients` (`food_id`, `ingredient_id`, `quantity_required`, `cost_price`)
            VALUES (?, ?, ?, ?)");
        if (!$ingredientStmt) throw new Exception('Ingredient insert prepare failed: ' . $conn->error);

        foreach ($_SESSION['recipe'] as $ingredient) {
            $ingredientId = (int)$ingredient['id'];
            $quantityRequired = (float)$ingredient['quantity'];
            $costPrice = (float)$ingredient['cost'];

            $verifyStmt->bind_param("i", $ingredientId);
            $verifyStmt->execute();
            $verifyStmt->store_result();

            if ($verifyStmt->num_rows === 0) {
                throw new Exception("Ingredient ID $ingredientId does not exist");
            }

            $ingredientStmt->bind_param("iisd", $food_id, $ingredientId, $quantityRequired, $costPrice);
            if (!$ingredientStmt->execute()) {
                throw new Exception('Ingredient insert execute failed: ' . $ingredientStmt->error);
            }
        }
    }

    // Process food group items
    if (!empty($_SESSION['food_items'])) {
        $groupStmt = $conn->prepare("INSERT INTO `food_group_items` (`food_id`, `quantity`, `cost_price`) VALUES (?, ?, ?)");
        if (!$groupStmt) throw new Exception('Group items prepare failed: ' . $conn->error);

        foreach ($_SESSION['food_items'] as $item) {
            $quantity = (float)$item['quantity'];
            $itemCostPrice = (float)$item['food_cost'] * $quantity;

            $groupStmt->bind_param("iid", $food_id, $quantity, $itemCostPrice);
            if (!$groupStmt->execute()) {
                throw new Exception('Group item insert failed: ' . $groupStmt->error);
            }
        }
    }

    $conn->commit();
    unset($_SESSION['recipe'], $_SESSION['food_items']);
    $response['success'] = true;
    $response['message'] = 'Food item added successfully';
    $response['food_id'] = $food_id;

} catch (Exception $e) {
    $conn->rollback();
    $response['message'] = $e->getMessage();

    if ($imagePath && file_exists($imagePath)) {
        unlink($imagePath);
    }
} finally {
    if ($stmt instanceof mysqli_stmt) $stmt->close();
    if ($verifyStmt instanceof mysqli_stmt) $verifyStmt->close();
    if ($ingredientStmt instanceof mysqli_stmt) $ingredientStmt->close();
    if ($groupStmt instanceof mysqli_stmt) $groupStmt->close();
    $conn->close();
}

echo json_encode($response);
?>
