# 🔥 Fiction Ignition — Setup Guide

## What's in this package

```
fiction-ignition/
├── index.html              ← Home page
├── app.html                ← Prompt generator app
├── pricing.html            ← Pricing page
├── checkout.html           ← Square payment checkout
├── about.html              ← About page
├── .htaccess               ← URL routing + security
├── css/                    ← Stylesheets
├── js/
│   ├── auth.js             ← Auth client (talks to PHP backend)
│   ├── shared.js           ← Nav, modals, session display
│   └── app.js              ← Prompt generator logic
├── images/                 ← Logo + icon
├── admin/
│   └── index.php           ← Admin dashboard
└── api/
    ├── schema.sql          ← Run this first to create the DB
    ├── .env.example        ← Copy to .env and fill in
    ├── composer.json       ← PHP dependencies
    ├── auth/index.php      ← Register, login, logout, verify
    ├── generate/index.php  ← AI prompt generation (server-side)
    ├── subscription/index.php ← Square subscription management
    ├── webhook/square.php  ← Square webhook receiver
    └── lib/
        ├── config.php      ← DB, session, helpers
        ├── mailer.php      ← Email sending (PHPMailer)
        └── square.php      ← Square API wrapper
```

---

## Step 1 — Server Requirements

- PHP 8.1 or higher
- MySQL 8.0+ or MariaDB 10.6+
- mod_rewrite enabled (Apache) or equivalent (Nginx)
- Composer (https://getcomposer.org)
- SSL certificate (required for Square payments)
- cURL extension enabled in PHP

---

## Step 2 — Database

1. Create a MySQL database and user:
```sql
CREATE DATABASE fiction_ignition CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'fi_user'@'localhost' IDENTIFIED BY 'your_strong_password';
GRANT ALL PRIVILEGES ON fiction_ignition.* TO 'fi_user'@'localhost';
FLUSH PRIVILEGES;
```

2. Run the schema:
```bash
mysql -u fi_user -p fiction_ignition < api/schema.sql
```

---

## Step 3 — Environment Config

```bash
cp api/.env.example api/.env
```

Then edit `api/.env` and fill in every value. Key ones:

| Key | Where to find it |
|-----|-----------------|
| `APP_URL` | Your domain, e.g. `https://fictionignition.com` |
| `DB_*` | Your MySQL credentials |
| `SQUARE_ACCESS_TOKEN` | Square Developer Dashboard → Credentials |
| `SQUARE_APP_ID` | Square Developer Dashboard → Credentials |
| `SQUARE_LOCATION_ID` | Square Dashboard → Locations |
| `SQUARE_WEBHOOK_SIGNATURE_KEY` | Square Dashboard → Webhooks (set after Step 6) |
| `SQUARE_PLAN_*` | Square Dashboard → Subscriptions → Plans (see Step 5) |
| `ANTHROPIC_API_KEY` | https://console.anthropic.com |
| `MAIL_*` | Your SMTP credentials |
| `ADMIN_EMAILS` | Comma-separated list of admin email addresses |

---

## Step 4 — Install PHP Dependencies

```bash
cd api/
composer install
```

This installs:
- **PHPMailer** — email sending
- **square/square** — Square SDK (optional, the site uses raw cURL but the SDK is available)

---

## Step 5 — Create Square Subscription Plans

In [Square Developer Dashboard](https://developer.squareup.com):

1. Go to **Subscriptions → Catalog Plans**
2. Create three plans:

| Plan | Price | Billing |
|------|-------|---------|
| Starter | $2.99 | Monthly |
| Writer | $6.99 | Monthly |
| Author Pro | $9.99 | Monthly |

3. Copy each plan's **Plan Variation ID** into your `.env`:
```
SQUARE_PLAN_STARTER=your_plan_variation_id
SQUARE_PLAN_WRITER=your_plan_variation_id
SQUARE_PLAN_AUTHOR_PRO=your_plan_variation_id
```

---

## Step 6 — Square Webhook

In Square Developer Dashboard → **Webhooks → Add Webhook**:

- **URL:** `https://yourdomain.com/api/webhook/square.php`
- **Events to subscribe:**
  - `subscription.activated`
  - `subscription.updated`
  - `subscription.deactivated`

Copy the **Signature Key** into your `.env` as `SQUARE_WEBHOOK_SIGNATURE_KEY`.

---

## Step 7 — Update checkout.html

Open `checkout.html` and replace the placeholder values near the bottom:

```javascript
const SQUARE_APP_ID   = 'sandbox-sq0idb-REPLACE_WITH_YOUR_APP_ID';
const SQUARE_LOCATION = 'REPLACE_WITH_YOUR_LOCATION_ID';
```

Also switch the Square SDK script tag from sandbox to production when ready:
```html
<!-- Sandbox (testing): -->
<script src="https://sandbox.web.squarecdn.com/v1/square.js"></script>

<!-- Production (live): -->
<script src="https://web.squarecdn.com/v1/square.js"></script>
```

---

## Step 8 — Enable Live Backend in app.js

Once your PHP backend is running, open `js/app.js` and change:

```javascript
const BACKEND_LIVE = false;  // ← change to true
```

This switches prompt generation from demo mode to the real Anthropic API call through your PHP server.

---

## Step 9 — Admin Access

Add your email to `.env`:
```
ADMIN_EMAILS=your@email.com,other@email.com
```

Then visit: `https://yourdomain.com/admin/`

You'll be redirected to sign in first. The admin dashboard lets you:
- View all users and their tiers
- Change a user's tier manually (dropdown)
- Delete users
- Resend verification emails
- Monitor Square webhook events
- See daily/monthly prompt usage stats

---

## Step 10 — Gmail SMTP Setup (if using Gmail)

1. Go to your Google Account → Security → 2-Step Verification → App Passwords
2. Create an app password for "Mail"
3. Use that 16-character password as `MAIL_PASSWORD` in `.env`
4. Set `MAIL_HOST=smtp.gmail.com` and `MAIL_PORT=587`

> Gmail has a 500 email/day limit. For production volume, use SendGrid, Mailgun, or Postmark instead.

---

## Sandbox Testing

Use Square's sandbox card numbers:
- **Visa (success):** `4111 1111 1111 1111`
- **Mastercard (success):** `5105 1051 0510 5100`
- **Any expiry** in the future, **any CVV**

Create a test user, verify their email, go to `/checkout.html`, pick a plan, enter the sandbox card. The subscription activates, the webhook fires, and the user's tier updates.

---

## Security Checklist Before Going Live

- [ ] `.env` is NOT in a publicly accessible directory (it's inside `api/` which has `.htaccess` protection)
- [ ] `SESSION_COOKIE_SECURE=true` in `.env`
- [ ] SSL certificate installed and working
- [ ] Switch Square from sandbox to production credentials
- [ ] Switch Square JS SDK from sandbox URL to production URL in `checkout.html`
- [ ] Set `BACKEND_LIVE = true` in `js/app.js`
- [ ] Change `APP_ENV=production` in `.env`
- [ ] Set `ADMIN_EMAILS` to your real email in `.env`

---

## Email Flow

| Trigger | Email sent |
|---------|-----------|
| User registers | Verification link email |
| User clicks verify link | Welcome + "account ready" email |
| Payment succeeds | Subscription confirmation email |

All email templates are in `api/lib/mailer.php` and are fully customizable.

---

## User Registration Flow

1. User fills in name, email, password → clicks "Create Free Account"
2. Frontend calls `POST /api/auth/?action=register`
3. PHP creates the user in DB with `email_verified = 0`
4. PHP generates a token, stores in `email_tokens` table
5. PHP sends verification email with link to `/api/auth/?action=verify&token=xxx`
6. User clicks link → PHP sets `email_verified = 1`, redirects to `/app.html?verified=1`
7. App shows "Email verified! You can now sign in." banner
8. User signs in → session cookie set → full access

---

## Payment Flow

1. User visits `/checkout.html?plan=writer`
2. Square Web Payments SDK renders a card input field
3. User enters card → clicks Subscribe
4. JS calls `squareCard.tokenize()` → gets a one-time card nonce
5. JS sends nonce + plan to `POST /api/subscription/?action=checkout`
6. PHP creates Square Customer + saves card + creates Subscription
7. PHP updates user's `tier` in DB
8. PHP sends confirmation email
9. Square fires `subscription.activated` webhook → PHP processes it
10. User sees success message, tier updates in nav

---

## Nginx Config (if not using Apache)

```nginx
location /api/ {
    try_files $uri $uri/ /api/$1/index.php?$query_string;
}

location ~ /api/lib/ {
    deny all;
}

location ~ \.env$ {
    deny all;
}
```
