<?php
// add_to_favorites.php

// Include the database connection file
require_once 'config.php';

// Set content type to JSON for API-like response
header('Content-Type: application/json');

// Check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Get and sanitize input
    // Using intval for IDs to ensure they are integers
    $customer_id = isset($_POST['customer_id']) ? intval($_POST['customer_id']) : 0;
    $menu_item_id = isset($_POST['menu_item_id']) ? intval($_POST['menu_item_id']) : 0; // Assuming 'id' from your request is the menu_item_id

    // Basic validation
    if ($customer_id <= 0 || $menu_item_id <= 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid customer ID or menu item ID provided.']);
        exit;
    }

    // Check if the item is already a favorite for this customer to prevent duplicates
    $check_sql = "SELECT COUNT(*) FROM favorites WHERE fav_customer_id = ? AND menu_item_id = ?";
    $check_stmt = $conn->prepare($check_sql);
    if ($check_stmt === false) {
        echo json_encode(['success' => false, 'message' => 'Failed to prepare check statement: ' . $conn->error]);
        $conn->close();
        exit;
    }
    $check_stmt->bind_param("ii", $customer_id, $menu_item_id);
    $check_stmt->execute();
    $check_stmt->bind_result($count);
    $check_stmt->fetch();
    $check_stmt->close();

    if ($count > 0) {
        echo json_encode(['success' => true, 'message' => 'Menu item is already in favorites for this customer.']);
        $conn->close();
        exit;
    }

    // Prepare an SQL INSERT statement using prepared statements to prevent SQL injection
    $sql = "INSERT INTO favorites (fav_customer_id, menu_item_id) VALUES (?, ?)";

    if ($stmt = $conn->prepare($sql)) {
        // Bind parameters
        // 'ii' indicates that both parameters are integers
        $stmt->bind_param("ii", $customer_id, $menu_item_id);

        // Execute the statement
        if ($stmt->execute()) {
            if ($stmt->affected_rows > 0) {
                echo json_encode(['success' => true, 'message' => 'Menu item added to favorites successfully.']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to add menu item to favorites. No rows affected.']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Error executing statement: ' . $stmt->error]);
        }

        // Close the statement
        $stmt->close();
    } else {
        echo json_encode(['success' => false, 'message' => 'Error preparing statement: ' . $conn->error]);
    }

    // Close the database connection
    $conn->close();
} else {
    // If it's not a POST request, respond with an error
    echo json_encode(['success' => false, 'message' => 'Invalid request method. Only POST requests are allowed.']);
}
