<?php
/**
 * Firebase Authentication Handler
 * Handles Firebase token verification and user management
 */

require_once '../core.php';

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

// Get POST data
$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';

try {
    switch ($action) {
        case 'verify_token':
            verifyFirebaseToken($input);
            break;
            
        case 'social_login':
            handleSocialLogin($input);
            break;
            
        case 'otp_login':
            handleOTPLogin($input);
            break;
            
        case 'link_account':
            linkSocialAccount($input);
            break;
            
        default:
            throw new Exception('Invalid action');
    }
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

/**
 * Verify Firebase ID Token
 */
function verifyFirebaseToken($data) {
    global $connect;
    
    $idToken = $data['idToken'] ?? '';
    $provider = $data['provider'] ?? 'email';
    
    if (empty($idToken)) {
        throw new Exception('ID token is required');
    }
    
    // In production, verify token with Firebase Admin SDK
    // For now, we'll decode the JWT payload (client-side verification already done)
    $tokenParts = explode('.', $idToken);
    if (count($tokenParts) !== 3) {
        throw new Exception('Invalid token format');
    }
    
    $payload = json_decode(base64_decode($tokenParts[1]), true);
    
    if (!$payload) {
        throw new Exception('Invalid token payload');
    }
    
    // Extract user data
    $firebaseUid = $payload['user_id'] ?? $payload['sub'] ?? '';
    $email = $payload['email'] ?? '';
    $name = $payload['name'] ?? '';
    $phone = $payload['phone_number'] ?? '';
    $emailVerified = $payload['email_verified'] ?? false;
    
    // Create or update user
    $user = createOrUpdateUser([
        'firebase_uid' => $firebaseUid,
        'email' => $email,
        'name' => $name,
        'phone' => $phone,
        'provider' => $provider,
        'email_verified' => $emailVerified
    ]);
    
    if ($user) {
        // Create session
        createUserSession($user);
        
        echo json_encode([
            'success' => true,
            'user' => [
                'id' => $user['user_id'],
                'name' => $user['user_name'],
                'email' => $user['user_email']
            ]
        ]);
    } else {
        throw new Exception('Failed to create user session');
    }
}

/**
 * Handle Social Login (Google/Facebook)
 */
function handleSocialLogin($data) {
    global $connect;
    
    $provider = $data['provider'] ?? '';
    $userData = $data['userData'] ?? [];
    
    if (empty($provider) || empty($userData)) {
        throw new Exception('Provider and user data are required');
    }
    
    $firebaseUid = $userData['uid'] ?? '';
    $email = $userData['email'] ?? '';
    $name = $userData['displayName'] ?? '';
    $photoURL = $userData['photoURL'] ?? '';
    
    // Create or update user
    $user = createOrUpdateUser([
        'firebase_uid' => $firebaseUid,
        'email' => $email,
        'name' => $name,
        'provider' => $provider,
        'photo_url' => $photoURL,
        'email_verified' => true
    ]);
    
    if ($user) {
        createUserSession($user);
        
        echo json_encode([
            'success' => true,
            'user' => [
                'id' => $user['user_id'],
                'name' => $user['user_name'],
                'email' => $user['user_email']
            ],
            'redirect' => SITE_URL
        ]);
    } else {
        throw new Exception('Failed to create user');
    }
}

/**
 * Handle OTP Login
 */
function handleOTPLogin($data) {
    global $connect;
    
    $phoneNumber = $data['phoneNumber'] ?? '';
    $name = $data['name'] ?? '';
    $firebaseUid = $data['firebaseUid'] ?? '';
    
    if (empty($phoneNumber)) {
        throw new Exception('Phone number is required');
    }
    
    // Create or update user
    $user = createOrUpdateUser([
        'firebase_uid' => $firebaseUid,
        'phone' => $phoneNumber,
        'name' => $name,
        'provider' => 'phone',
        'email_verified' => false
    ]);
    
    if ($user) {
        createUserSession($user);
        
        echo json_encode([
            'success' => true,
            'user' => [
                'id' => $user['user_id'],
                'name' => $user['user_name'],
                'phone' => $user['user_mobile']
            ],
            'redirect' => SITE_URL
        ]);
    } else {
        throw new Exception('Failed to create user');
    }
}

/**
 * Create or Update User in Database
 */
function createOrUpdateUser($data) {
    global $connect;
    
    $firebaseUid = $data['firebase_uid'] ?? '';
    $email = $data['email'] ?? '';
    $phone = $data['phone'] ?? '';
    $name = $data['name'] ?? 'User';
    $provider = $data['provider'] ?? 'email';
    $photoURL = $data['photo_url'] ?? '';
    $emailVerified = $data['email_verified'] ?? false;
    
    // Check if user exists by Firebase UID
    if (!empty($firebaseUid)) {
        $stmt = $connect->prepare("SELECT * FROM users WHERE firebase_uid = :firebase_uid LIMIT 1");
        $stmt->execute([':firebase_uid' => $firebaseUid]);
        $existingUser = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($existingUser) {
            // Update existing user
            $updateStmt = $connect->prepare("
                UPDATE users 
                SET user_name = :name,
                    user_mobile = :phone,
                    firebase_provider = :provider,
                    firebase_photo_url = :photo_url,
                    user_last_login = NOW()
                WHERE firebase_uid = :firebase_uid
            ");
            
            $updateStmt->execute([
                ':name' => $name,
                ':phone' => $phone,
                ':provider' => $provider,
                ':photo_url' => $photoURL,
                ':firebase_uid' => $firebaseUid
            ]);
            
            return $existingUser;
        }
    }
    
    // Check if user exists by email
    if (!empty($email)) {
        $stmt = $connect->prepare("SELECT * FROM users WHERE user_email = :email LIMIT 1");
        $stmt->execute([':email' => $email]);
        $existingUser = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($existingUser) {
            // Link Firebase account to existing user
            $updateStmt = $connect->prepare("
                UPDATE users 
                SET firebase_uid = :firebase_uid,
                    firebase_provider = :provider,
                    firebase_photo_url = :photo_url,
                    user_mobile = :phone,
                    user_last_login = NOW()
                WHERE user_email = :email
            ");
            
            $updateStmt->execute([
                ':firebase_uid' => $firebaseUid,
                ':provider' => $provider,
                ':photo_url' => $photoURL,
                ':phone' => $phone,
                ':email' => $email
            ]);
            
            return $existingUser;
        }
    }
    
    // Check if user exists by phone
    if (!empty($phone)) {
        $stmt = $connect->prepare("SELECT * FROM users WHERE user_mobile = :phone LIMIT 1");
        $stmt->execute([':phone' => $phone]);
        $existingUser = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($existingUser) {
            // Link Firebase account
            $updateStmt = $connect->prepare("
                UPDATE users 
                SET firebase_uid = :firebase_uid,
                    firebase_provider = :provider,
                    user_last_login = NOW()
                WHERE user_mobile = :phone
            ");
            
            $updateStmt->execute([
                ':firebase_uid' => $firebaseUid,
                ':provider' => $provider,
                ':phone' => $phone
            ]);
            
            return $existingUser;
        }
    }
    
    // Create new user
    $insertStmt = $connect->prepare("
        INSERT INTO users (
            user_name, 
            user_email, 
            user_mobile,
            firebase_uid,
            firebase_provider,
            firebase_photo_url,
            user_status,
            user_created_at,
            user_last_login
        ) VALUES (
            :name,
            :email,
            :phone,
            :firebase_uid,
            :provider,
            :photo_url,
            1,
            NOW(),
            NOW()
        )
    ");
    
    $insertStmt->execute([
        ':name' => $name,
        ':email' => $email,
        ':phone' => $phone,
        ':firebase_uid' => $firebaseUid,
        ':provider' => $provider,
        ':photo_url' => $photoURL
    ]);
    
    // Get newly created user
    $userId = $connect->lastInsertId();
    $stmt = $connect->prepare("SELECT * FROM users WHERE user_id = :id LIMIT 1");
    $stmt->execute([':id' => $userId]);
    
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

/**
 * Create User Session
 */
function createUserSession($user) {
    $_SESSION['signedin'] = true;
    $_SESSION['user_email'] = $user['user_email'];
    $_SESSION['user_name'] = $user['user_name'];
    $_SESSION['user_id'] = $user['user_id'];
    $_SESSION['firebase_uid'] = $user['firebase_uid'] ?? '';
    $_SESSION['firebase_provider'] = $user['firebase_provider'] ?? '';
}

/**
 * Link Social Account to Existing User
 */
function linkSocialAccount($data) {
    global $connect;
    
    if (!isset($_SESSION['user_id'])) {
        throw new Exception('User not logged in');
    }
    
    $userId = $_SESSION['user_id'];
    $provider = $data['provider'] ?? '';
    $firebaseUid = $data['firebaseUid'] ?? '';
    
    if (empty($provider) || empty($firebaseUid)) {
        throw new Exception('Provider and Firebase UID are required');
    }
    
    $stmt = $connect->prepare("
        UPDATE users 
        SET firebase_uid = :firebase_uid,
            firebase_provider = :provider
        WHERE user_id = :user_id
    ");
    
    $stmt->execute([
        ':firebase_uid' => $firebaseUid,
        ':provider' => $provider,
        ':user_id' => $userId
    ]);
    
    echo json_encode([
        'success' => true,
        'message' => 'Account linked successfully'
    ]);
}

?>
