<?php
require_once '../../lib/Response.php';
require_once '../../lib/Auth.php';
require_once '../../lib/Database.php';

header('Content-Type: application/json');

$response = new Response();
$auth = new Auth();
$db = Database::getConnection();

try {
    $method = $_SERVER['REQUEST_METHOD'];
    
    switch ($method) {
        case 'POST':
            $data = json_decode(file_get_contents('php://input'), true);
            
            if (!isset($data['firebase_token'])) {
                $response->error('Firebase token is required', 400);
                break;
            }
            
            $firebaseToken = $data['firebase_token'];
            $name = isset($data['name']) ? $data['name'] : null;
            $email = isset($data['email']) ? $data['email'] : null;
            
            // Verify Firebase token with Firebase Admin SDK
            // For now, we'll use a simple verification by making a request to Google's token info endpoint
            $tokenInfo = verifyFirebaseToken($firebaseToken);
            
            if (!$tokenInfo || !isset($tokenInfo['user_id'])) {
                $response->error('Invalid Firebase token', 401);
                break;
            }
            
            $firebaseUid = $tokenInfo['user_id'];
            $email = $tokenInfo['email'] ?? $email;
            $name = $tokenInfo['name'] ?? $name;
            
            if (!$email) {
                $response->error('Email is required', 400);
                break;
            }
            
            // Check if user exists with this Firebase UID
            $stmt = $db->prepare("SELECT * FROM users WHERE firebase_uid = ?");
            $stmt->execute([$firebaseUid]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$user) {
                // Check if user exists with this email (for existing users who are using Google Sign-In)
                $stmt = $db->prepare("SELECT * FROM users WHERE email = ?");
                $stmt->execute([$email]);
                $user = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($user) {
                    // Update existing user with Firebase UID
                    $stmt = $db->prepare("UPDATE users SET firebase_uid = ?, last_login = NOW() WHERE id = ?");
                    $stmt->execute([$firebaseUid, $user['id']]);
                    $user['firebase_uid'] = $firebaseUid;
                } else {
                    // Create new user
                    $name = $name ?: 'Google User';
                    $stmt = $db->prepare("INSERT INTO users (name, email, firebase_uid, role, last_login) VALUES (?, ?, ?, 'customer', NOW())");
                    $stmt->execute([$name, $email, $firebaseUid]);
                    $userId = $db->lastInsertId();
                    
                    // Fetch the newly created user
                    $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
                    $stmt->execute([$userId]);
                    $user = $stmt->fetch(PDO::FETCH_ASSOC);
                }
            } else {
                // Update last login for existing user
                $stmt = $db->prepare("UPDATE users SET last_login = NOW() WHERE id = ?");
                $stmt->execute([$user['id']]);
            }
            
            // Generate JWT token for our backend
            $jwtToken = $auth->generateToken([
                'user_id' => $user['id'],
                'email' => $user['email'],
                'role' => $user['role'],
                'name' => $user['name']
            ]);
            
            $response->success([
                'token' => $jwtToken,
                'user' => [
                    'id' => $user['id'],
                    'name' => $user['name'],
                    'email' => $user['email'],
                    'role' => $user['role'],
                    'phone' => $user['phone']
                ]
            ]);
            break;
            
        default:
            $response->error('Method not allowed', 405);
            break;
    }
} catch (Exception $e) {
    $response->error('Server error: ' . $e->getMessage(), 500);
}

/**
 * Verify Firebase ID token using Google's token info endpoint
 * Note: In production, you should use Firebase Admin SDK for proper verification
 */
function verifyFirebaseToken($idToken) {
    $url = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=" . $idToken;
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode === 200) {
        $tokenInfo = json_decode($response, true);
        
        // Verify the token is from our Firebase project (you should replace with your actual audience)
        // $expectedAudience = "your-firebase-project-id";
        // if ($tokenInfo['aud'] !== $expectedAudience) {
        //     return false;
        // }
        
        // Check if token is expired
        if (isset($tokenInfo['exp']) && $tokenInfo['exp'] < time()) {
            return false;
        }
        
        return $tokenInfo;
    }
    
    return false;
}
?>