<?php
/**
 * Authentication API Endpoints
 * v1/auth
 */

global $method, $input, $apiResponse, $apiAuth, $user;

switch ($method) {
    case 'POST':
        // Login endpoint
        if (empty($segments[2])) {
            $username = $input['username'] ?? '';
            $password = $input['password'] ?? '';
            
            if (empty($username) || empty($password)) {
                $apiResponse->error('Username and password required', 400);
            }
            
            // Authenticate user
            $sql = "SELECT u.*, r.role_name FROM users u 
                   INNER JOIN roles r ON u.role_id = r.role_id 
                   WHERE u.username = ? AND u.is_active = 1 AND u.deleted_at IS NULL";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("s", $username);
            $stmt->execute();
            $result = $stmt->get_result();
            $dbUser = $result->fetch_assoc();
            
            if ($dbUser && password_verify($password, $dbUser['password_hash'])) {
                // Generate API token
                $tokenResult = $apiAuth->generateToken($dbUser['user_id'], 30);
                
                if ($tokenResult['success']) {
                    // Update last login
                    $updateSql = "UPDATE users SET last_login = NOW() WHERE user_id = ?";
                    $updateStmt = $conn->prepare($updateSql);
                    $updateStmt->bind_param("i", $dbUser['user_id']);
                    $updateStmt->execute();
                    
                    // Get member_id if user is a member
                    $member_id = null;
                    if ($dbUser['role_name'] === 'MEMBER') {
                        $memberSql = "SELECT member_id FROM members WHERE user_id = ?";
                        $memberStmt = $conn->prepare($memberSql);
                        $memberStmt->bind_param("i", $dbUser['user_id']);
                        $memberStmt->execute();
                        $memberResult = $memberStmt->get_result();
                        $member = $memberResult->fetch_assoc();
                        $member_id = $member['member_id'] ?? null;
                    }
                    
                    $apiResponse->success([
                        'token' => $tokenResult['token'],
                        'expires_at' => $tokenResult['expires_at'],
                        'user' => [
                            'user_id' => $dbUser['user_id'],
                            'username' => $dbUser['username'],
                            'email' => $dbUser['email'],
                            'role' => $dbUser['role_name'],
                            'member_id' => $member_id
                        ]
                    ], 'Login successful');
                } else {
                    $apiResponse->error('Failed to generate token', 500);
                }
            } else {
                $apiResponse->error('Invalid credentials', 401);
            }
        }
        break;
        
    case 'GET':
        // Get current user info
        if (empty($segments[2])) {
            $profile = json_decode($user['profile'] ?? '{}', true);
            
            $apiResponse->success([
                'user_id' => $user['user_id'],
                'username' => $user['username'],
                'email' => $user['email'],
                'role' => $user['role_name'],
                'profile' => $profile,
                'last_login' => $user['last_login']
            ], 'User information retrieved');
        }
        break;
        
    default:
        $apiResponse->error('Method not allowed', 405);
}
