# Bank Statement Converter - Setup Guide

## URL Structure

All URLs are clean (without .php extensions) and scoped to `/bank/public/`:
- `/bank/public/` - Converter (requires login or anonymous)
- `/bank/public/dashboard` - User dashboard (requires login)
- `/bank/public/admin` - Admin panel (requires admin role)
- `/bank/public/login` - Login & signup page
- `/bank/public/logout` - Logout (clears session/cookie)

### 1. Create MySQL/MariaDB Database

```bash
mysql -u root -p
```

```sql
CREATE DATABASE bank_converter CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
use bank_converter;
```

### 2. Import Schema

Copy and paste the contents of `database.sql` into the MySQL client, or run:

```bash
mysql -u root -p bank_converter < /path/to/database.sql
```

### 3. Configure Database Connection

Copy `.env.example` to `.env` in the project root:

```bash
cp .env.example .env
```

Edit `.env` with your database credentials:

```
DB_HOST=localhost
DB_PORT=3306
DB_NAME=bank_converter
DB_USER=root
DB_PASS=your_password
```

The system will automatically load this file when connecting to the database. The `.env` file is parsed and loaded each time a database connection is established.

## User Roles

### Admin User (Pre-created)
- **Username:** admin
- **Email:** admin@example.com
- **Password:** admin123 (⚠️ CHANGE THIS IMMEDIATELY IN PRODUCTION!)

### Anonymous User (No Account)
- Get 5 free conversions with a 24-hour cookie
- Cookie stores conversion count (httpOnly for security)
- No database entry or authentication needed
- Can create an account anytime to upgrade

### Default Billing Plans

1. **Free Trial** - 3 documents (included with new account)
2. **Starter** - 50 documents/month - $4.99
3. **Professional** - 500 documents/month - $29.99
4. **Enterprise** - 2000 documents/month - $99.99

## Usage

### Anonymous Access (No Account Required)
- Visit `/bank/public/` directly and a 24-hour anonymous cookie is created automatically
- You can convert up to 5 PDFs within 24 hours
- Conversions are NOT tracked in database
- Badge shows: ⏱️ 5 free conversions
- Create an account anytime to upgrade

### User Registration & Signup Email Verification
- Visit `/bank/public/login?signup=1` to create an account
- After signup, check your email for a verification link
- Click the verification link to confirm your email
- Once verified, you can log in and access the converter with 3 free conversions
- After using free conversions, upgrade to a paid plan (currently "Contact Us")

### File Conversion
- Log in or visit `/bank/public/` to upload PDFs
- Anonymous users get 5 auto-created via cookie; Logged-in users use account credits
- Each conversion uses 1 credit
- Converted CSV is downloaded directly to browser
- Conversion history for logged-in users is tracked in database

### Admin Dashboard
- Log in as admin and visit `/bank/public/admin`
- Search for users by email
- View user details, credits, and conversion history
- Add credits manually to user accounts
- Supports assigning credits to specific billing plans for audit purposes

### User Dashboard
- Log in and visit `/bank/public/dashboard`
- View remaining conversions
- View billing plans (with "Contact Us" for premium)
- See conversion history and credit usage logs

## API Endpoints

### POST /bank/public/convert-api
Converts a PDF file to CSV. Requires login OR anonymous session.

**Request:**
- `file` (multipart) - PDF file
- `csrf_token` (string) - CSRF token from session
- `password` (string, optional) - PDF password for encrypted files

**Response:**
```json
{
  "success": true,
  "error": null,
  "data": {
    "fileName": "statement.pdf",
    "csv": "Date,Description,Amount,Balance\n...",
    "bankType": "FNB",
    "transactions": 135,
    "safeName": "statement_converted.csv",
    "creditsRemaining": 2,
    "isAnonymous": false
  }
}
```

- For authenticated users: credits deducted from account, conversion recorded in database
- For anonymous users: cookie-based counter updated, NO database record

## Features Implemented

✅ User registration and authentication with bcrypt password hashing
✅ Credit-based system (3 free initially, then purchase-required)
✅ Billing plans management
✅ Admin dashboard for user and credit management
✅ Conversion history tracking (with success/failure status)
✅ PDF encryption/decryption support
✅ FNB bank statement parsing
✅ CSRF token validation on all forms
✅ Responsive design with gradient UI

## Security Features

- ✅ Bcrypt password hashing (cost factor 10)
- ✅ CSRF token protection on all forms
- ✅ SQL injection prevention with prepared statements
- ✅ Session-based authentication
- ✅ Role-based access control (user/admin)
- ✅ File type validation (PDF only)
- ✅ No server-side file storage (ephemeral processing)

## Future Enhancements

- 🔲 Stripe/payment integration for automated billing
- 🔲 Email notifications for credit expiry
- 🔲 Batch API for automated conversions
- 🔲 Rate limiting per user/IP
- 🔲 File encryption at rest
- 🔲 CloudStorage integration (S3, etc.)
- 🔲 Additional bank parser support
- 🔲 CSV template customization

## Troubleshooting

### "Database connection failed"
- Check environment variables (DB_HOST, DB_NAME, DB_USER, DB_PASS)
- Verify MySQL is running: `mysql -u root -p -e "SELECT 1"`
- Check database was imported: `mysql -u root -p bank_converter -e "SHOW TABLES"`

### "No conversions remaining"
- User has exhausted their free/paid credits
- Admin can manually add credits in `/admin.php`

### "Invalid CSRF token"
- Session may have expired
- Try logging out and logging back in

### "Only PDF files are accepted"
- File uploaded is not a valid PDF
- Check file format and try again

## File Structure

```
/public
  ├── index.php                  # Main converter interface (requires login)
  ├── convert-api.php            # AJAX conversion endpoint (checks credits)
  ├── login.php                  # Login & signup page
  ├── logout.php                 # Logout handler
  ├── dashboard.php              # User dashboard (credits, history, billing)
  ├── admin.php                  # Admin panel (user management, credits)

/src
  ├── Database.php               # PDO connection singleton
  ├── Converter.php              # Main conversion class
  ├── User.php                   # User model with auth methods
  ├── BankDetector.php           # Bank detection logic
  ├── Auth.php                   # Session/auth management
  ├── BillingPlan.php            # Billing and credit tracking
  ├── Parsers/
  │   ├── FnbParser.php          # FNB-specific parsing
  │   ├── StandardBankParser.php # Standard Bank parsing
  │   └── ParserInterface.php    # Parser contract

/database.sql                   # MySQL schema and default data
```
