<?php
// social_login.php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once 'includes/db.php';
require_once __DIR__ . '/vendor/autoload.php';

// --- CONFIGURATION ---
// PASTE THE KEYS YOU GOT FROM STEP 1 HERE
$config = [
    'callback' => rtrim((isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]", '/') . '/social_login.php',
    'providers' => [
        'Google' => [
            'enabled' => true,
            'keys' => ['id' => 'YOUR_GOOGLE_CLIENT_ID', 'secret' => 'YOUR_GOOGLE_CLIENT_SECRET'],
        ],
        'Facebook' => [
            'enabled' => true,
            'keys' => ['id' => 'YOUR_FACEBOOK_APP_ID', 'secret' => 'YOUR_FACEBOOK_APP_SECRET'],
        ],
    ],
];

try {
    $hybridauth = new Hybridauth\Hybridauth($config);
    $provider = $_GET['provider'] ?? '';

    // Attempt to authenticate with the selected provider
    $adapter = $hybridauth->authenticate($provider);
    
    // Retrieve the user's profile
    $userProfile = $adapter->getUserProfile();

    if ($userProfile && isset($userProfile->identifier)) {
        $provider_name = $provider;
        $provider_id = $userProfile->identifier;
        $email = $userProfile->email;
        $full_name = $userProfile->displayName;

        // 1. Check if this social profile is already linked to an account
        $stmt = $conn->prepare("SELECT * FROM users WHERE provider_name = ? AND provider_id = ?");
        $stmt->bind_param("ss", $provider_name, $provider_id);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            // User exists, log them in
            $user = $result->fetch_assoc();
        } else {
            // 2. New social login. Check if the email address is already registered
            $stmt = $conn->prepare("SELECT * FROM users WHERE email = ?");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result->num_rows > 0) {
                // Email exists, link this social profile to that existing account
                $user = $result->fetch_assoc();
                $stmt_update = $conn->prepare("UPDATE users SET provider_name = ?, provider_id = ? WHERE id = ?");
                $stmt_update->bind_param("ssi", $provider_name, $provider_id, $user['id']);
                $stmt_update->execute();
            } else {
                // 3. This is a completely new user. Create their account.
                $stmt_insert = $conn->prepare("INSERT INTO users (full_name, email, provider_name, provider_id, role, status) VALUES (?, ?, ?, ?, 'customer', 'active')");
                $stmt_insert->bind_param("ssss", $full_name, $email, $provider_name, $provider_id);
                $stmt_insert->execute();
                $new_user_id = $conn->insert_id;
                
                // Fetch the new user record to log them in
                $stmt_fetch = $conn->prepare("SELECT * FROM users WHERE id = ?");
                $stmt_fetch->bind_param("i", $new_user_id);
                $stmt_fetch->execute();
                $user = $stmt_fetch->get_result()->fetch_assoc();
            }
        }
        
        // --- Create Session and Redirect to Dashboard ---
        session_regenerate_id(true);
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_name'] = $user['full_name'];
        $_SESSION['user_role'] = $user['role'];
        header("Location: dashboard/");
        exit();
    }
    
    $adapter->disconnect();

} catch (\Exception $e) {
    // On any error, log it and redirect the user back to the login page
    error_log('HybridAuth Error: ' . $e->getMessage());
    header("Location: login.php?error=social_login_failed");
    exit();
}
