<?php
header('Content-Type: application/json');
include 'config.php';
$userId = $_COOKIE['user_id'];
// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid JSON input']);
    exit;
}

try {
    // Validate required fields
    $requiredFields = ['bid', 'jcipher', 'jtitle', 'cover_letter', 'price'];
    foreach ($requiredFields as $field) {
        if (!isset($input[$field]) || empty($input[$field])) {
            echo json_encode(['status' => 'error', 'message' => "Missing required field: $field"]);
            exit;
        }
    }

    // Prepare data for insertion
    $bidData = [
        'user_id' => $userId,
        'bid' => $input['bid'],
        'jcipher' => $input['jcipher'],
        'jtitle' => $input['jtitle'],
        'cover_letter' => $input['cover_letter'],
        'price' => $input['price'],
        'jprice' => $input['jprice'] ?? null,
        'client' => isset($input['client']) ? json_encode($input['client']) : null,
        'jobType' => $input['jobType'] ?? null,
        'description' => $input['description'] ?? null,
        'skills' => isset($input['skills']) ? json_encode($input['skills']) : null,
        'created_at' => date('Y-m-d H:i:s'),
        'updated_at' => date('Y-m-d H:i:s')
    ];

    // Build SQL query
    $columns = implode(', ', array_keys($bidData));
    $placeholders = str_repeat('?,', count($bidData) - 1) . '?';
    
    $sql = "INSERT INTO upwork_bids_history ($columns) VALUES ($placeholders)";
    
    $stmt = $conn->prepare($sql);
    
    // Bind parameters
    $types = str_repeat('s', count($bidData)); // All strings
    $values = array_values($bidData);
    $stmt->bind_param($types, ...$values);
    
    // Execute query
    if ($stmt->execute()) {
        echo json_encode([
            'status' => 'success',
            'message' => 'Bid inserted successfully'
        ]);
    } else {
        echo json_encode([
            'status' => 'error',
            'message' => 'Failed to insert bid: ' . $stmt->error
        ]);
    }
    
} catch (Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>