<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');

$host = 'localhost'; 
$db   = 'u386163872_jwtcart'; 
$user = 'u386163872_dbadmin';
$pass = 'Shiro@13';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$db;charset=utf8mb4", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (\PDOException $e) {
    echo json_encode(['success' => false, 'error' => 'DB Connection failed']);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $email = $input['email'] ?? '';
    $type  = $input['type'] ?? 'cart'; // 'cart' or 'kyc'
    $data  = $input['data'] ?? [];

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

    if ($type === 'kyc') {
        $stmt = $pdo->prepare("INSERT INTO user_carts (email, kyc_data) VALUES (?, ?) ON DUPLICATE KEY UPDATE kyc_data = ?, updated_at = CURRENT_TIMESTAMP");
        $stmt->execute([$email, json_encode($data), json_encode($data)]);
    } else {
        $stmt = $pdo->prepare("INSERT INTO user_carts (email, cart_data) VALUES (?, ?) ON DUPLICATE KEY UPDATE cart_data = ?, updated_at = CURRENT_TIMESTAMP");
        $stmt->execute([$email, json_encode($data), json_encode($data)]);
    }
    echo json_encode(['success' => true]);

} elseif ($method === 'GET') {
    $email = $_GET['email'] ?? '';
    if (!$email) {
        echo json_encode(['success' => false, 'error' => 'Email required']);
        exit;
    }

    $stmt = $pdo->prepare("SELECT cart_data, kyc_data FROM user_carts WHERE email = ?");
    $stmt->execute([$email]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    echo json_encode([
        'success' => true, 
        'cart' => json_decode($row['cart_data'] ?? '[]', true),
        'kyc' => json_decode($row['kyc_data'] ?? '{}', true)
    ]);
}
?>