# Configuration Guide

## Application Settings

### 1. OAuth Configuration

In `app.py`, you can customize:

```python
# Line 39 - Change the port or domain
REDIRECT_URI = 'http://localhost:5000/oauth2callback'

# Line 43 - These are the required permissions
SCOPES = [
    'https://www.googleapis.com/auth/spreadsheets.readonly',
    'https://www.googleapis.com/auth/drive.readonly'
]
```

### 2. Session Configuration

```python
# Line 23 - Cookie security (set to True in production with HTTPS)
app.config['SESSION_COOKIE_SECURE'] = False

# Line 26 - Session lifetime in minutes
app.permanent_session_lifetime = timedelta(minutes=60)
```

### 3. Environment Variables (Optional)

To make the app more flexible, you can add a `.env` file:

```
FLASK_ENV=development
FLASK_DEBUG=True
GOOGLE_CLIENT_ID=your_client_id_here
GOOGLE_CLIENT_SECRET=your_client_secret_here
SECRET_KEY=your_secret_key_here
DATABASE_URL=optional_db_url
```

Then load in app.py:
```python
from dotenv import load_dotenv
load_dotenv()
SECRET_KEY = os.getenv('SECRET_KEY', 'default_key')
```

---

## Customizing the Dashboard

### Add New Filters

In `templates/dashboard.html`:

1. Add a new filter group in the "Filters" section:
```html
<div class="filter-group">
    <label for="newFilter">New Filter</label>
    <select id="newFilter" onchange="applyFilters()">
        <option value="all">All Items</option>
        {% for item in filters.new_items %}
        <option value="{{ item }}">{{ item }}</option>
        {% endfor %}
    </select>
</div>
```

2. Update `app.py` `dashboard()` route to add the filter:
```python
filters = {
    'clientes': sorted(sheets_data['Cliente'].unique().tolist()),
    'new_filter': sorted(sheets_data['YourColumn'].unique().tolist()),
    # ... other filters
}
```

3. Update `get_sheets_data()` route to filter by new parameter:
```python
new_filter = request.args.get('newfilter')
if new_filter and new_filter != 'all':
    df = df[df['YourColumn'] == new_filter]
```

### Customize Styling

Edit `templates/base.html` or `dashboard.html` `<style>` section:

```css
/* Change header color */
header {
    background: linear-gradient(135deg, #YOUR_COLOR1 0%, #YOUR_COLOR2 100%);
}

/* Change stat card accent */
.stat-card .value {
    color: #YOUR_COLOR;
}
```

### Add Chart/Visualization

1. Install Plotly: `pip install plotly`

2. Add to `app.py`:
```python
import plotly.graph_objects as go
import plotly.express as px

@app.route('/charts')
@login_required
def charts():
    creds = get_google_credentials()
    df = fetch_sheets_data(creds)
    
    # Create chart
    fig = px.bar(df, x='Mês', y='Faturaçao', title='Revenue by Month')
    
    return render_template('charts.html', 
                         chart=fig.to_html(include_plotlyjs='cdn'))
```

---

## Connecting Multiple Sheets

If you want to combine data from multiple Google Sheets:

```python
def fetch_multiple_sheets(creds, sheet_ids):
    """Fetch data from multiple sheets and combine"""
    all_data = []
    
    for sheet_id in sheet_ids:
        gc = gspread.authorize(creds)
        spreadsheet = gc.open_by_key(sheet_id)
        worksheet = spreadsheet.sheet1
        
        values = worksheet.get_all_values()
        headers = values[0]
        data = values[1:]
        
        df = pd.DataFrame(data, columns=headers)
        all_data.append(df)
    
    return pd.concat(all_data, ignore_index=True)
```

---

## Adding Authentication Levels

For different user permissions:

```python
# In app.py
ADMIN_EMAILS = ['admin@example.com']

def is_admin(email):
    return email in ADMIN_EMAILS

@app.route('/admin')
@login_required
def admin_panel():
    if not is_admin(current_user.id):
        return "Access Denied", 403
    
    return render_template('admin.html')
```

---

## Error Handling

To add custom error pages:

```python
@app.errorhandler(404)
def not_found(error):
    return render_template('error.html', 
                         error='Page Not Found',
                         code=404), 404

@app.errorhandler(500)
def server_error(error):
    return render_template('error.html', 
                         error='Server Error',
                         code=500), 500
```

---

## Performance Optimization

### Caching
```python
from flask_caching import Cache

cache = Cache(app, config={'CACHE_TYPE': 'simple'})

@app.route('/get-sheets-data')
@cache.cached(timeout=300)  # Cache for 5 minutes
@login_required
def get_sheets_data():
    # ... your code
```

### Database (Optional)
For large datasets, use SQLite:

```python
import sqlite3

def sync_to_db(df):
    """Save Google Sheets data to local SQLite"""
    conn = sqlite3.connect('sales.db')
    df.to_sql('sales_data', conn, if_exists='replace', index=False)
    conn.close()
```

---

## Deployment Configuration

### For Heroku
Create `Procfile`:
```
web: gunicorn app:app
```

Create `runtime.txt`:
```
python-3.9.13
```

### For Azure
Create `web.config`:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <handlers>
            <add name="PythonHandler" 
                 path="*" 
                 verb="*" 
                 modules="HttpPlatformHandler" 
                 scriptProcessor="D:\Python39\python.exe|D:\Python39\wfastcgi.py" 
                 resourceType="Unspecified" 
                 requireAccess="Script" />
        </handlers>
    </system.webServer>
</configuration>
```

### For Docker
Create `Dockerfile`:
```dockerfile
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "app.py"]
```

---

## Security Best Practices

1. **Environment Variables**
   - Never hardcode secrets
   - Use `.env` file (in `.gitignore`)

2. **HTTPS Only (Production)**
   - Set `SESSION_COOKIE_SECURE = True`
   - Use SSL/TLS certificate

3. **Secret Key**
   - Generate strong secret: `python -c "import secrets; print(secrets.token_hex(32))"`

4. **Rate Limiting**
   ```python
   from flask_limiter import Limiter
   limiter = Limiter(app, key_func=lambda: current_user.id)
   
   @limiter.limit("100 per hour")
   @app.route('/get-sheets-data')
   def get_sheets_data():
       # ...
   ```

5. **Input Validation**
   - Validate all user inputs
   - Use `bleach` library to sanitize

---

## Monitoring & Logging

```python
import logging
from logging.handlers import RotatingFileHandler

if not app.debug:
    file_handler = RotatingFileHandler('app.log', 
                                      maxBytes=10240000, 
                                      backupCount=10)
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s'
    ))
    app.logger.addHandler(file_handler)
    app.logger.setLevel(logging.INFO)
```

---

For more help, refer to:
- `README.md` - Full documentation
- `QUICKSTART.md` - Quick setup
- `DEVELOPMENT_SUMMARY.md` - Technical details
