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

// --- YOUR HOSTINGER DATABASE DETAILS ---
$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' => 'Database connection failed']);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'POST') {
    // 💾 SAVE KYC DATA
    $input = json_decode(file_get_contents('php://input'), true);
    $email = $input['email'] ?? '';
    $type  = $input['type'] ?? '';
    $data  = $input['data'] ?? [];

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

    if ($type === 'kyc') {
        // Insert new user KYC profile, or UPDATE existing profile if the email already exists
        $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)]);
        
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Invalid save type']);
    }

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

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

    if ($row && !empty($row['kyc_data'])) {
        echo json_encode(['success' => true, 'kyc' => json_decode($row['kyc_data'], true)]);
    } else {
        echo json_encode(['success' => true, 'kyc' => null]);
    }
}
?>