# AdMob API Manager - Complete Setup & Deployment Guide

## 📋 Project Overview

This is a **complete, production-ready PHP web application** that provides full access to Google AdMob API v1 features through a professional dashboard interface.

### ✅ Features Included

**Authentication & Security**
- Google OAuth 2.0 authentication
- Secure token management with auto-refresh
- Session management
- HTTPS-ready

**Dashboard & Analytics**
- Real-time earnings, impressions, and clicks
- Multi-dimensional views (by app, country, format)
- Performance metrics
- Data visualization containers

**Report Management**
- Network Report generation (custom dimensions & metrics)
- Mediation Report generation
- Custom report creation & scheduling
- CSV export functionality
- Report caching for performance

**Data Management**
- Apps inventory synchronization
- Ad Units management
- Account information retrieval
- Data caching (1-hour duration)

**Settings & Configuration**
- OAuth token management
- Application preferences
- Cache management
- Auto-refresh settings

---

## 🚀 Complete Installation Guide

### Step 1: Create Google Cloud Project

1. **Go to Google Cloud Console:**
   - Visit https://console.cloud.google.com/
   - Create a new project: "AdMob Manager"
   - Enable billing (required for API access)

2. **Enable AdMob API:**
   - Go to APIs & Services → Library
   - Search for "AdMob API"
   - Click "Enable"

3. **Create OAuth 2.0 Credentials:**
   - Go to Credentials → Create Credentials → OAuth client ID
   - If prompted, configure OAuth consent screen:
     - User type: **External**
     - App name: AdMob Manager
     - Add your email as Support & Developer contact
   
   - Application type: **Web application**
   - Name: AdMob Manager Web
   - Add Authorized redirect URIs:
     ```
     https://yourdomain.com/admob-manager/callback.php
     http://localhost/admob-manager/callback.php  (for testing)
     ```
   - Download JSON credentials

4. **Copy Client Credentials:**
   - Open the downloaded JSON file
   - Find: `client_id` and `client_secret`
   - You'll need these in Step 4

---

### Step 2: Database Setup

**For phpMyAdmin or direct MySQL access:**

```sql
-- Create database
CREATE DATABASE admob_manager;
USE admob_manager;

-- OAuth Tokens Table
CREATE TABLE oauth_tokens (
    id INT PRIMARY KEY AUTO_INCREMENT,
    user_id VARCHAR(255) UNIQUE NOT NULL,
    access_token LONGTEXT NOT NULL,
    refresh_token LONGTEXT,
    token_expiry DATETIME,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    KEY (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Cached Reports Table
CREATE TABLE cached_reports (
    id INT PRIMARY KEY AUTO_INCREMENT,
    report_name VARCHAR(255),
    report_data LONGTEXT,
    generated_at DATETIME,
    cache_expiry DATETIME,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    KEY (cache_expiry)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Account Info Table
CREATE TABLE account_info (
    id INT PRIMARY KEY AUTO_INCREMENT,
    publisher_id VARCHAR(255) UNIQUE NOT NULL,
    account_name VARCHAR(255),
    timezone VARCHAR(50),
    currency_code VARCHAR(3),
    account_data LONGTEXT,
    last_updated DATETIME,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    KEY (publisher_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Apps Inventory Table
CREATE TABLE apps_inventory (
    id INT PRIMARY KEY AUTO_INCREMENT,
    app_id VARCHAR(255) UNIQUE NOT NULL,
    app_name VARCHAR(255),
    package_name VARCHAR(255),
    platform VARCHAR(50),
    store_id VARCHAR(255),
    app_data LONGTEXT,
    last_updated DATETIME,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    KEY (app_id),
    KEY (platform)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Ad Units Table
CREATE TABLE ad_units (
    id INT PRIMARY KEY AUTO_INCREMENT,
    ad_unit_id VARCHAR(255) UNIQUE NOT NULL,
    ad_unit_name VARCHAR(255),
    app_id VARCHAR(255),
    ad_format VARCHAR(50),
    ad_types TEXT,
    ad_unit_data LONGTEXT,
    last_updated DATETIME,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    KEY (ad_unit_id),
    KEY (app_id),
    KEY (ad_format),
    FOREIGN KEY (app_id) REFERENCES apps_inventory(app_id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```

---

### Step 3: Upload Files to Server

**Directory Structure:**
```
/var/www/html/admob-manager/
├── index.php
├── login.php
├── logout.php
├── callback.php
├── config/
│   ├── config.php          (EDIT THIS)
│   └── database.php
├── src/
│   ├── Database.php
│   ├── OAuth.php
│   ├── AdMobAPI.php
│   └── ReportGenerator.php
├── api/
│   ├── reports.php
│   ├── apps.php
│   ├── ad-units.php
│   └── account.php
├── pages/
│   ├── dashboard.php
│   ├── reports.php
│   ├── apps.php
│   ├── ad-units.php
│   ├── account.php
│   └── settings.php
├── logs/                   (create this dir, chmod 755)
├── tmp/                    (create this dir, chmod 755)
└── README.md
```

**Required Directories (create and chmod 755):**
```bash
mkdir -p logs tmp
chmod 755 logs tmp
```

---

### Step 4: Configure Application

**Edit `config/config.php`:**

```php
<?php
// Database Configuration
define('DB_HOST', 'localhost');        // Your database host
define('DB_USER', 'root');             // Your database user
define('DB_PASSWORD', 'password');     // Your database password
define('DB_NAME', 'admob_manager');    // Database name

// Google OAuth (from Step 1)
define('GOOGLE_CLIENT_ID', 'YOUR_CLIENT_ID_HERE.apps.googleusercontent.com');
define('GOOGLE_CLIENT_SECRET', 'YOUR_CLIENT_SECRET_HERE');
define('GOOGLE_REDIRECT_URI', 'https://yourdomain.com/admob-manager/callback.php');

// URL Configuration
define('APP_URL', 'https://yourdomain.com/admob-manager/');

// Cache & Session
define('CACHE_DURATION', 3600);  // 1 hour
define('SESSION_TIMEOUT', 7200); // 2 hours

// Debug Mode (set to false in production)
define('DEBUG_MODE', false);

?>
```

---

### Step 5: Install Composer Dependencies (if using)

```bash
cd /var/www/html/admob-manager/
composer require google/apiclient:^2.18.0
```

Or use the included standalone classes (no dependencies required).

---

### Step 6: Set File Permissions

```bash
cd /var/www/html/admob-manager/

# Make files readable
chmod 644 *.php
chmod 644 config/*.php
chmod 644 src/*.php
chmod 644 api/*.php

# Make directories writable for cache/logs
chmod 755 logs
chmod 755 tmp
chmod 755 api

# Make config readable only
chmod 600 config/config.php
```

---

## 🔐 Security Best Practices

1. **Always use HTTPS** in production
2. **Store credentials securely** (use environment variables):
   ```php
   define('GOOGLE_CLIENT_ID', getenv('GOOGLE_CLIENT_ID'));
   define('GOOGLE_CLIENT_SECRET', getenv('GOOGLE_CLIENT_SECRET'));
   ```

3. **Restrict API access:**
   - Add `.htaccess` to `/api/` directory:
   ```
   <FilesMatch "\.php$">
       Require all granted
   </FilesMatch>
   ```

4. **Enable SSL/TLS certificates** (Let's Encrypt recommended)

5. **Regular backups** of database

6. **Keep PHP updated** (7.4+ required)

---

## 📱 Usage Instructions

### First Time Setup

1. **Visit:** `https://yourdomain.com/admob-manager/`
2. **Click:** "Sign in with Google"
3. **Authorize:** Allow access to your AdMob account
4. **Dashboard loaded:** You'll see your account data

### Dashboard Features

**Dashboard Tab:**
- View earnings, impressions, clicks
- Switch between views (by app, country, format)
- Refresh data manually

**Reports Tab:**
- **Network Report:** Custom dimensions & metrics
- **Mediation Report:** Ad source performance
- **Custom Report:** Schedule recurring reports

**Apps Tab:**
- View all connected apps
- Sync apps from AdMob
- View app details

**Ad Units Tab:**
- Manage all ad units
- Filter by app/format/status
- View ad unit performance

**Settings Tab:**
- OAuth token management
- Application preferences
- Cache management

---

## 🔄 API Endpoints

All endpoints require valid session/authentication.

### Reports API

**Generate Network Report:**
```bash
POST /api/reports.php?action=network
Content-Type: application/json

{
    "start_date": "2024-01-01",
    "end_date": "2024-01-31",
    "dimensions": ["DATE", "APP", "COUNTRY"],
    "metrics": ["IMPRESSIONS", "CLICKS", "ESTIMATED_EARNINGS"]
}
```

**Generate Mediation Report:**
```bash
POST /api/reports.php?action=mediation
Content-Type: application/json

{
    "start_date": "2024-01-01",
    "end_date": "2024-01-31",
    "dimensions": ["DATE", "AD_SOURCE"],
    "metrics": ["IMPRESSIONS", "CLICKS", "ESTIMATED_EARNINGS"]
}
```

**Get Cached Reports:**
```bash
GET /api/reports.php?action=cached
```

### Apps API

**List Apps:**
```bash
GET /api/apps.php?action=list
```

**Sync Apps from AdMob:**
```bash
GET /api/apps.php?action=sync
```

**Get App Details:**
```bash
GET /api/apps.php?action=get&id=ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy
```

### Ad Units API

**List Ad Units:**
```bash
GET /api/ad-units.php?action=list
```

**List by App:**
```bash
GET /api/ad-units.php?action=list&app_id=app-id-here
```

**Sync Ad Units:**
```bash
GET /api/ad-units.php?action=sync
```

---

## 🛠️ Troubleshooting

### Issue: "Invalid state parameter"
**Solution:** Clear browser cookies and try login again

### Issue: "Token expired"
**Solution:** The app auto-refreshes tokens. If it fails, disconnect and reconnect.

### Issue: "No apps found"
**Solution:** Click "Refresh Apps List" to sync from AdMob API

### Issue: Database connection error
**Solution:** Verify credentials in `config/config.php` and check database is running

### Issue: HTTPS redirect issues
**Solution:** Update `GOOGLE_REDIRECT_URI` to use HTTPS in production

---

## 📊 Data Flow Diagram

```
User Login
    ↓
Google OAuth (login.php)
    ↓
callback.php (exchange code for token)
    ↓
Save token to database (oauth_tokens)
    ↓
Dashboard loads (index.php)
    ↓
JavaScript calls API endpoints
    ↓
PHP validates token (OAuth::ensureValidToken)
    ↓
API calls AdMob API (AdMobAPI class)
    ↓
Cache response to database
    ↓
Return JSON to frontend
    ↓
JavaScript renders data
```

---

## 🚀 Production Deployment

### Recommended Hosting
- **Shared Hosting:** Bluehost, HostGator, SiteGround
- **VPS:** DigitalOcean, Linode, Vultr
- **Cloud:** AWS (EC2), Google Cloud, Azure

### Server Requirements
- **PHP:** 7.4 or higher
- **MySQL:** 5.7 or higher
- **Extensions:** cURL, PDO, OpenSSL
- **Memory:** Minimum 256MB
- **Storage:** 1GB+ (for logs and cache)

### Deployment Steps

```bash
# 1. SSH to server
ssh user@your-server.com

# 2. Navigate to web root
cd /var/www/html/

# 3. Clone/upload files
git clone <repo-url> admob-manager
# OR
scp -r ./admob-manager user@your-server.com:/var/www/html/

# 4. Set permissions
cd admob-manager
chmod -R 755 .
chmod 600 config/config.php
chmod 755 logs tmp api

# 5. Create database
mysql -u root -p < setup/database.sql

# 6. Configure app
nano config/config.php  # Edit with your credentials

# 7. Test
curl https://yourdomain.com/admob-manager/login.php
```

---

## 📞 Support & Additional Resources

- **AdMob API Docs:** https://developers.google.com/admob/api
- **Google OAuth 2.0:** https://developers.google.com/identity/protocols/oauth2
- **PHP cURL:** https://www.php.net/manual/en/book.curl.php
- **MySQL Docs:** https://dev.mysql.com/doc/

---

## 📝 License

This project is provided as-is for personal and commercial use.

---

**Created:** January 2026
**Version:** 1.0
**Status:** Production Ready ✓
