<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/database.php';

// Check authentication
$user = null;
$auth_token = $_COOKIE['rcp_auth'] ?? ($_SERVER['HTTP_AUTHORIZATION'] ?? null);

if ($auth_token) {
    try {
        $pdo = Database::getInstance()->getConnection();
        
        // Remove 'Bearer ' prefix if present
        if (strpos($auth_token, 'Bearer ') === 0) {
            $auth_token = substr($auth_token, 7);
        }
        
        $stmt = $pdo->prepare("SELECT session_data FROM user_sessions WHERE session_id = ? AND expires_at > NOW()");
        $stmt->execute([$auth_token]);
        $session_data = $stmt->fetchColumn();
        
        if ($session_data) {
            $user = json_decode($session_data, true);
        }
    } catch (Throwable $t) {
        error_log("Session error: " . $t->getMessage());
    }
}

if (!$user || !isset($user['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$userId = $user['user_id'];

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid input data']);
    exit();
}

// Validate required fields
$required = ['name', 'unit', 'price'];
foreach ($required as $field) {
    if (empty($input[$field])) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => "Missing required field: $field"]);
        exit();
    }
}

try {
    $pdo = Database::getInstance()->getConnection();
    
    // Check if ingredient already exists for this user
    $checkStmt = $pdo->prepare("SELECT id FROM ingredients WHERE name = ? AND user_id = ?");
    $checkStmt->execute([trim($input['name']), $userId]);
    
    if ($checkStmt->fetch()) {
        http_response_code(409); // Conflict
        echo json_encode(['success' => false, 'message' => 'Ingredient with this name already exists']);
        exit();
    }
    
    // Insert ingredient with all fields including price_updated_at
    $stmt = $pdo->prepare("
        INSERT INTO ingredients (
            user_id, 
            name, 
            unit, 
            price, 
            previous_price,
            category, 
            supplier_info,
            price_updated_at,
            created_at,
            updated_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
    ");
    
    $price = floatval($input['price']);
    
    $success = $stmt->execute([
        $userId,
        trim($input['name']),
        trim($input['unit']),
        $price,
        null, // previous_price is NULL for new ingredients
        trim($input['category'] ?? ''),
        trim($input['supplier_info'] ?? ''),
        date('Y-m-d H:i:s') // price_updated_at - set to current time
    ]);
    
    if ($success) {
        // Get the newly created ingredient ID
        $ingredientId = $pdo->lastInsertId();
        
        echo json_encode([
            'success' => true,
            'message' => 'Ingredient created successfully',
            'ingredient_id' => $ingredientId,
            'data' => [
                'id' => $ingredientId,
                'name' => trim($input['name']),
                'unit' => trim($input['unit']),
                'price' => $price,
                'category' => trim($input['category'] ?? ''),
                'supplier_info' => trim($input['supplier_info'] ?? ''),
                'user_id' => $userId,
                'price_updated_at' => date('Y-m-d H:i:s')
            ]
        ]);
    } else {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Failed to create ingredient']);
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Error creating ingredient: ' . $e->getMessage()
    ]);
}
?>