<?php
/**
 * API: User Profile Endpoints
 * Routes:
 * GET /api/v1/user/profile - Get user info
 * POST /api/v1/user/profile - Update profile
 * POST /api/v1/user/password - Change password
 * GET /api/v1/user/transactions - Get transaction history
 */

// Check authentication
$apiKey = $_GET['api_key'] ?? $_POST['api_key'] ?? null;
if (!$apiKey) {
    http_response_code(401);
    echo json_encode(['error' => 'API key required']);
    exit;
}

$stmt = $db->prepare('SELECT id FROM users WHERE api_key = ? AND status = "active"');
$stmt->execute([$apiKey]);
$user = $stmt->fetch(\PDO::FETCH_ASSOC);

if (!$user) {
    http_response_code(401);
    echo json_encode(['error' => 'Invalid API key']);
    exit;
}

$userId = $user['id'];

switch ($method) {
    case 'GET':
        if ($action === 'profile') {
            getProfile($db, $userId);
        } elseif ($action === 'transactions') {
            getTransactions($db, $userId);
        }
        break;
        
    case 'POST':
        if ($action === 'profile') {
            updateProfile($db, $userId, $input);
        } elseif ($action === 'password') {
            changePassword($db, $userId, $input);
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
}

/**
 * Get user profile
 */
function getProfile($db, $userId) {
    try {
        $stmt = $db->prepare('
            SELECT id, username, email, full_name, balance, primary_currency,
                   account_type, status, created_at, last_login, telegram_user_id
            FROM users
            WHERE id = ?
        ');
        $stmt->execute([$userId]);
        $user = $stmt->fetch(\PDO::FETCH_ASSOC);
        
        if (!$user) {
            http_response_code(404);
            echo json_encode(['error' => 'User not found']);
            return;
        }
        
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'data' => $user
        ]);
        
    } catch (\Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
}

/**
 * Update user profile
 */
function updateProfile($db, $userId, $input) {
    try {
        $fullName = $input['full_name'] ?? null;
        $email = $input['email'] ?? null;
        $primaryCurrency = $input['primary_currency'] ?? 'UGX';
        
        if (!$fullName && !$email && !$primaryCurrency) {
            http_response_code(400);
            echo json_encode(['error' => 'No fields to update']);
            return;
        }
        
        // Build update query
        $updates = [];
        $params = [];
        
        if ($fullName) {
            $updates[] = 'full_name = ?';
            $params[] = $fullName;
        }
        
        if ($email) {
            // Check if email is unique
            $checkStmt = $db->prepare('SELECT id FROM users WHERE email = ? AND id != ?');
            $checkStmt->execute([$email, $userId]);
            if ($checkStmt->fetch()) {
                http_response_code(409);
                echo json_encode(['error' => 'Email already in use']);
                return;
            }
            $updates[] = 'email = ?';
            $params[] = $email;
        }
        
        if ($primaryCurrency) {
            $updates[] = 'primary_currency = ?';
            $params[] = $primaryCurrency;
        }
        
        $params[] = $userId;
        $updateQuery = 'UPDATE users SET ' . implode(', ', $updates) . ' WHERE id = ?';
        
        $db->prepare($updateQuery)->execute($params);
        
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'message' => 'Profile updated'
        ]);
        
    } catch (\Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
}

/**
 * Change password
 */
function changePassword($db, $userId, $input) {
    try {
        $currentPassword = $input['current_password'] ?? null;
        $newPassword = $input['new_password'] ?? null;
        $confirmPassword = $input['confirm_password'] ?? null;
        
        if (!$currentPassword || !$newPassword || !$confirmPassword) {
            http_response_code(400);
            echo json_encode(['error' => 'All password fields required']);
            return;
        }
        
        if ($newPassword !== $confirmPassword) {
            http_response_code(400);
            echo json_encode(['error' => 'Passwords do not match']);
            return;
        }
        
        if (strlen($newPassword) < 8) {
            http_response_code(400);
            echo json_encode(['error' => 'Password must be at least 8 characters']);
            return;
        }
        
        // Get user password
        $stmt = $db->prepare('SELECT password FROM users WHERE id = ?');
        $stmt->execute([$userId]);
        $user = $stmt->fetch(\PDO::FETCH_ASSOC);
        
        // Verify current password
        if (!password_verify($currentPassword, $user['password'])) {
            http_response_code(401);
            echo json_encode(['error' => 'Current password is incorrect']);
            return;
        }
        
        // Update password
        $hashedPassword = password_hash($newPassword, PASSWORD_BCRYPT);
        $db->prepare('UPDATE users SET password = ? WHERE id = ?')->execute([$hashedPassword, $userId]);
        
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'message' => 'Password changed successfully'
        ]);
        
    } catch (\Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
}

/**
 * Get transaction history
 */
function getTransactions($db, $userId) {
    try {
        $page = $_GET['page'] ?? 1;
        $limit = $_GET['limit'] ?? 20;
        
        $page = max(1, intval($page));
        $limit = min(100, max(1, intval($limit)));
        $offset = ($page - 1) * $limit;
        
        // Get total
        $countStmt = $db->prepare('SELECT COUNT(*) as total FROM transactions WHERE user_id = ?');
        $countStmt->execute([$userId]);
        $total = $countStmt->fetch(\PDO::FETCH_ASSOC)['total'];
        
        // Get transactions
        $stmt = $db->prepare('
            SELECT id, type, amount, reference, description, created_at
            FROM transactions
            WHERE user_id = ?
            ORDER BY created_at DESC
            LIMIT ? OFFSET ?
        ');
        $stmt->execute([$userId, $limit, $offset]);
        $transactions = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'data' => $transactions,
            'pagination' => [
                'page' => $page,
                'limit' => $limit,
                'total' => $total
            ]
        ]);
        
    } catch (\Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
}
?>
