<?php
header('Content-Type: application/json; charset=utf-8');
include('../connection.php');

date_default_timezone_set('Asia/Dhaka');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid request method'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$rechargeId = trim($_POST['recharge_id'] ?? '');
$userId = trim($_POST['user_id'] ?? '');

if ($rechargeId === '' && $userId === '') {
    echo json_encode([
        'status' => 'error',
        'message' => 'Recharge ID is required'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$stmt = $conn->prepare('SELECT id, user_id, recharge_id, username, name, address, phone FROM users WHERE recharge_id = ? OR user_id = ? LIMIT 1');
$stmt->bind_param('ss', $rechargeId, $userId);
$stmt->execute();
$result = $stmt->get_result();

if ($result && $row = $result->fetch_assoc()) {
    echo json_encode([
        'status' => 'success',
        'message' => 'Login successful',
        'user' => [
            'id' => (int) $row['id'],
            'user_id' => $row['user_id'],
            'recharge_id' => $row['recharge_id'],
            'username' => $row['username'],
            'name' => $row['name'],
            'address' => $row['address'],
            'phone' => $row['phone'],
            'created_at' => date('d-m-Y h:i A')
        ]
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

echo json_encode([
    'status' => 'error',
    'message' => 'Invalid recharge ID'
], JSON_UNESCAPED_UNICODE);
