<?php
// ajax_check_user.php - Check if user exists and get saved payment methods
// File location: /bidwheels.net/product/ajax_check_user.php

require_once '../includes/functions.php';

header('Content-Type: application/json');

$email = isset($_POST['email']) ? sanitize($_POST['email']) : '';

if (empty($email)) {
    echo json_encode(['exists' => false, 'error' => 'Email is required']);
    exit();
}

// Check if user exists
$user = fetchOne("SELECT id, name, phone, address FROM users WHERE email = '$email' AND is_dummy = 0");

if ($user) {
    // Get saved payment methods
    $payment_methods = fetchAll("
        SELECT upm.id, upm.payment_data, upm.is_default, pm.method_name
        FROM user_payment_methods upm
        JOIN payment_methods pm ON upm.payment_method_id = pm.id
        WHERE upm.user_id = {$user['id']}
        ORDER BY upm.is_default DESC, upm.created_at DESC
    ");
    
    echo json_encode([
        'exists' => true,
        'user_id' => $user['id'],
        'user_info' => [
            'name' => $user['name'],
            'phone' => $user['phone'],
            'address' => $user['address']
        ],
        'payment_methods' => $payment_methods
    ]);
} else {
    echo json_encode(['exists' => false]);
}
?>