# Setup Guide - Google Authentication

## 📋 Checklist Setup

### ✅ Backend (Laravel) - SUDAH SELESAI

- [x] API endpoint `/api/signupWithGoogle` dibuat
- [x] API endpoint `/api/login` sudah support Google
- [x] Database migration dibuat
- [x] Model UserCompany sudah diupdate
- [x] Dokumentasi API lengkap

**Yang perlu dilakukan:**
```bash
# 1. Jalankan migration
php artisan migrate

# 2. Test API (opsional)
php artisan serve
```

**TIDAK PERLU:**
- ❌ Install Laravel Socialite
- ❌ Setup Google Client ID/Secret di .env
- ❌ Konfigurasi config/services.php
- ❌ Install package tambahan

---

### 🎯 Frontend/Mobile App - PERLU SETUP

**Yang HARUS dilakukan di App:**

#### 1. Setup Google Sign-In SDK

**Android (Kotlin/Java):**
```gradle
// app/build.gradle
dependencies {
    implementation 'com.google.android.gms:play-services-auth:20.7.0'
}
```

**iOS (Swift):**
```swift
// Install via CocoaPods
pod 'GoogleSignIn'
```

**React/Web:**
```bash
npm install @react-oauth/google
```

#### 2. Dapatkan Google Client ID

1. Buka https://console.cloud.google.com
2. Create project atau pilih yang ada
3. Enable **Google+ API** atau **Google Sign-In API**
4. **Credentials** → **Create Credentials** → **OAuth 2.0 Client ID**
5. Pilih Application type:
   - Android: Masukkan package name & SHA-1 certificate
   - iOS: Masukkan Bundle ID
   - Web: Masukkan authorized JavaScript origins
6. Copy **Client ID**

#### 3. Implement Google Sign-In di App

**Android Example:**
```kotlin
// Configure Google Sign-In
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
    .requestEmail()
    .requestIdToken(getString(R.string.default_web_client_id))
    .build()

val googleSignInClient = GoogleSignIn.getClient(this, gso)

// Sign in
val signInIntent = googleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)

// Handle result
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if (requestCode == RC_SIGN_IN) {
        val task = GoogleSignIn.getSignedInAccountFromIntent(data)
        val account = task.getResult(ApiException::class.java)

        // Kirim ke backend
        signupWithGoogle(
            name = account.displayName,
            email = account.email,
            googleId = account.id,
            photo = account.photoUrl.toString()
        )
    }
}

// Function untuk hit API backend
fun signupWithGoogle(name: String, email: String, googleId: String, photo: String) {
    val json = JSONObject().apply {
        put("user_name", name)
        put("user_email", email)
        put("google_id", googleId)
        put("user_photo", photo)
    }

    val request = Request.Builder()
        .url("https://your-api.com/api/signupWithGoogle")
        .post(json.toString().toRequestBody("application/json".toMediaType()))
        .build()

    // Execute request...
}
```

**React Example:**
```jsx
import { GoogleOAuthProvider, GoogleLogin } from '@react-oauth/google';
import { jwtDecode } from 'jwt-decode';

function App() {
  const handleGoogleSuccess = async (credentialResponse) => {
    // Decode JWT token dari Google
    const decoded = jwtDecode(credentialResponse.credential);

    // Kirim ke backend
    const response = await fetch('https://your-api.com/api/signupWithGoogle', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        user_name: decoded.name,
        user_email: decoded.email,
        google_id: decoded.sub,
        user_photo: decoded.picture,
      })
    });

    const data = await response.json();
    if (data.isSuccess) {
      // Save access_token
      localStorage.setItem('token', data.data.access_token);
      // Redirect to dashboard
    }
  };

  return (
    <GoogleOAuthProvider clientId="YOUR_GOOGLE_CLIENT_ID_HERE">
      <GoogleLogin
        onSuccess={handleGoogleSuccess}
        onError={() => console.log('Login Failed')}
      />
    </GoogleOAuthProvider>
  );
}
```

---

## 🔄 Flow Lengkap

```
┌────────────┐
│    User    │
└─────┬──────┘
      │ 1. Klik "Sign in with Google"
      ▼
┌─────────────────────┐
│   Mobile/Web App    │
│  (Google Sign-In    │
│   SDK installed)    │
└──────┬──────────────┘
       │ 2. Redirect ke Google OAuth
       ▼
┌─────────────────────┐
│  Google OAuth Page  │ ← User login dengan Google account
└──────┬──────────────┘
       │ 3. User approve
       ▼
┌─────────────────────┐
│   Mobile/Web App    │ ← Dapat: name, email, googleId, photo
└──────┬──────────────┘
       │ 4. POST /api/signupWithGoogle
       ▼
┌─────────────────────┐
│  Backend (Laravel)  │
│  - Validasi email   │
│  - Create company   │
│  - Create user      │
│  - Auto login       │
│  - Return token     │
└──────┬──────────────┘
       │ 5. Response dengan access_token
       ▼
┌─────────────────────┐
│   Mobile/Web App    │
│  - Save token       │
│  - Redirect home    │
└─────────────────────┘
```

---

## 🧪 Testing

### 1. Test Backend API

```bash
# Test signup
curl -X POST http://localhost:8000/api/signupWithGoogle \
  -H "Content-Type: application/json" \
  -d '{
    "user_name": "Test User",
    "user_email": "test@gmail.com",
    "google_id": "123456789"
  }'

# Expected response
{
  "isSuccess": true,
  "message": "Google signup successful!",
  "emailVerified": true,
  "data": {
    "user": {...},
    "company": {...},
    "access_token": "eyJ0eXAiOiJKV1..."
  }
}
```

### 2. Test Login

```bash
curl -X POST http://localhost:8000/api/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@gmail.com",
    "is_google": true
  }'
```

---

## ❓ FAQ

**Q: Apakah perlu Google Client Secret di backend?**
A: ❌ Tidak perlu. Client-side auth tidak butuh secret di backend.

**Q: Bagaimana cara verify user benar-benar dari Google?**
A: ✅ Gunakan GoogleTokenVerifier (optional) dengan id_token dari app.

**Q: Apakah bisa user signup dengan email biasa lalu login dengan Google?**
A: ❌ Tidak. System check auth_provider. Email signup harus login dengan password.

**Q: Bagaimana jika user sudah punya account email ingin link ke Google?**
A: Perlu implement link account feature (belum ada di implementasi saat ini).

**Q: Client ID untuk Android dan iOS sama atau beda?**
A: 🔄 Beda. Tiap platform perlu Client ID sendiri di Google Console.

**Q: Apakah perlu enable Google+ API?**
A: ✅ Ya, atau minimal "Google Sign-In API" di Google Cloud Console.

---

## 📞 Support

Jika ada pertanyaan atau issue:
1. Check dokumentasi: `GOOGLE_AUTH_API.md`
2. Check migration: `database/migrations/2026_02_05_113553_add_google_auth_fields_to_tb_user_table.php`
3. Check API Controller: `app/Http/Controllers/ApiController.php` method `signupWithGoogle()`

---

## 🎉 Summary

### Backend (DONE ✅)
- Migration created
- API ready
- No Google credentials needed

### Frontend (TODO 📝)
- Install Google Sign-In SDK
- Get Google Client ID from Google Console
- Implement sign in button
- Handle callback and send to backend
- Save access token
