================================================================================
MULTICASTING DEAL FINDER & BROADCASTER - TECHNICAL DOCUMENTATION
================================================================================

VERSION: 1.0
LAST UPDATED: 2024

================================================================================
TABLE OF CONTENTS
================================================================================

1. Application Overview
2. System Requirements
3. File Structure and Descriptions
4. Installation Instructions
5. Database Setup
6. Configuration
7. CDN Resources Used
8. Code Walkthrough
9. Debugging Guide
10. Extending the Application
11. Security Considerations

================================================================================
1. APPLICATION OVERVIEW
================================================================================

The Multicasting Deal Finder & Broadcaster is a multi-user SaaS application 
designed to help users find and broadcast deals across multiple platforms. 
It provides four main tools:

- Platform Selector Tool: Recommends best platforms based on niche and location
- Deal Script Generator: Creates customized outreach scripts for multiple platforms
- Margin Calculator: Calculates profit margins and income projections
- Provider Vetter Checklist Generator: Creates custom checklists for vetting service providers

The application uses OpenAI's GPT-4o-mini API for AI-powered content generation.
Users must provide their own OpenAI API key to use the AI features.

================================================================================
2. SYSTEM REQUIREMENTS
================================================================================

RECOMMENDED PHP VERSION: PHP 8.0 or higher

REQUIRED PHP EXTENSIONS:
- PDO (PHP Data Objects)
- pdo_mysql
- json
- curl
- mbstring
- session

MYSQL VERSION: MySQL 5.7+ or MariaDB 10.2+

WEB SERVER: Apache 2.4+ or Nginx 1.18+

BROWSER COMPATIBILITY:
- Chrome 90+
- Firefox 88+
- Safari 14+
- Edge 90+

================================================================================
3. FILE STRUCTURE AND DESCRIPTIONS
================================================================================

ROOT DIRECTORY FILES:
--------------------

config.php
- Central configuration file for the application
- Contains database connection settings
- Defines application constants
- Includes core functions for database operations and API calls
- Contains the callOpenAI() function for making API requests
- Includes logging and input sanitization functions

database.sql
- SQL file containing all database table structures
- Includes users, sales, and application-specific tables
- No sample data included (as per requirements)
- Ready to import via phpMyAdmin or command line

index.php (PROTECTED)
- Main dashboard/landing page after login
- Displays overview of all four tools
- Shows API key configuration status
- Requires protect.php to ensure user is logged in

header.php
- Common header file included by all pages
- Contains HTML head section with CDN links
- Navigation menu with links to all tools
- Ensures consistent styling across all pages

footer.php
- Common footer file included by all pages
- Contains closing HTML tags
- Includes CDN script links (jQuery, Bootstrap)
- Loads application JavaScript file

api_settings.php (PROTECTED)
- Allows users to add/update their OpenAI API key
- Stores API key in the users table (user_claude_apikey column)
- Provides instructions for obtaining an API key
- Includes security warnings about API key usage

platform_selector.php (PROTECTED)
- Interface for the Platform Selector Tool
- User inputs niche and location
- Calls API to generate platform recommendations
- Displays results with copy functionality

script_generator.php (PROTECTED)
- Interface for the Script Generator Tool
- User inputs service type and optional target platforms
- Generates customized outreach scripts
- Provides multiple script versions (short, medium, long)

margin_calculator.php (PROTECTED)
- Interface for the Margin Calculator Tool
- User inputs service cost and retail price
- Calculates profit margins and markup percentages
- Generates monthly income projections at various volumes
- Does NOT use AI (pure JavaScript calculation)

vetter_checklist.php (PROTECTED)
- Interface for the Provider Vetter Checklist Tool
- User inputs service category and specific needs
- Generates comprehensive vetting checklist
- Includes print functionality

API DIRECTORY (api/):
--------------------

api/generate_platforms.php (PROTECTED)
- Backend endpoint for Platform Selector Tool
- Receives niche and location via POST
- Constructs prompt and calls OpenAI API
- Saves results to platform_searches table
- Returns JSON response with generated content

api/generate_script.php (PROTECTED)
- Backend endpoint for Script Generator Tool
- Receives service type and target platforms via POST
- Generates multiple script versions
- Saves results to script_generations table
- Returns JSON response

api/generate_checklist.php (PROTECTED)
- Backend endpoint for Vetter Checklist Tool
- Receives service category and specific needs via POST
- Generates comprehensive checklist
- Saves results to vetter_checklists table
- Returns JSON response

CSS DIRECTORY (css/):
--------------------

css/style.css
- Custom styles for the application
- Dark color scheme with proper contrast ratios
- Responsive design for mobile devices
- Styled form elements with sufficient visibility
- Loading overlay styles
- Print-friendly styles

JAVASCRIPT DIRECTORY (js/):
---------------------------

js/app.js
- Main application JavaScript file
- Handles form submissions for all tools
- Makes AJAX calls to API endpoints
- Manages loading overlays and result displays
- Provides copy-to-clipboard functionality
- Includes error handling and user feedback

FILES PROVIDED BY YOU (NOT CREATED):
-----------------------------------

protect.php
- Protection script that must be included at the top of all protected pages
- Checks if user is logged in
- Sets $userid variable for the logged-in user
- Redirects to login.php if user is not authenticated

user-lib.php
- User authentication library classes
- Provides user management functionality

login.php
- User login page
- Authenticates users and starts sessions

logout.php
- Logs out the user
- Destroys session and redirects to login page

register.php
- User registration page
- Creates new user accounts

================================================================================
4. INSTALLATION INSTRUCTIONS
================================================================================

STEP 1: UPLOAD FILES
--------------------
1. Extract the application zip file
2. Upload all files to your web server using FTP or control panel file manager
3. You can install in root directory (public_html) or a subdirectory
4. Ensure all file permissions are set correctly (644 for files, 755 for directories)

STEP 2: CREATE DATABASE
------------------------
1. Log in to your hosting control panel (cPanel, Plesk, etc.)
2. Navigate to MySQL Databases or Database section
3. Create a new database (e.g., multicasting_db)
4. Create a database user with a strong password
5. Grant ALL PRIVILEGES to the user for the database
6. Note down the database name, username, and password

STEP 3: IMPORT DATABASE STRUCTURE
----------------------------------
1. Open phpMyAdmin from your control panel
2. Select the database you created
3. Click the "Import" tab
4. Click "Choose File" and select database.sql from the uploaded files
5. Click "Go" to import
6. Verify that all tables were created successfully (users, sales, platform_searches, 
   script_generations, margin_calculations, vetter_checklists)

STEP 4: CONFIGURE APPLICATION
------------------------------
1. Open config.php in a text editor
2. Update the database connection settings:
   - USER_DB_HOST (usually 'localhost')
   - USER_DB_NAME (your database name)
   - USER_DB_USER (your database username)
   - USER_DB_PASSWORD (your database password)
3. Update the admin credentials if desired:
   - $adminuser
   - $adminpassword
4. Save the file

STEP 5: SET FILE PERMISSIONS
-----------------------------
Ensure the web server can write to the log files:
- chmod 644 error.log (create if doesn't exist)
- chmod 644 app.log (create if doesn't exist)

STEP 6: TEST THE APPLICATION
-----------------------------
1. Navigate to your installation URL in a web browser
2. You should be redirected to login.php (provided by you)
3. Register a new account or log in with existing credentials
4. After successful login, you'll be redirected to index.php
5. Go to API Settings and add your OpenAI API key
6. Test each tool to ensure everything works

================================================================================
5. DATABASE SETUP
================================================================================

DATABASE TABLES:

users (REQUIRED - Multi-user system)
- Stores user account information
- Structure defined in multi-user requirements
- user_claude_apikey column stores OpenAI API keys
- DO NOT modify this structure

sales (REQUIRED - Multi-user system)
- Stores sales transactions
- Structure defined in multi-user requirements
- Used by the existing user management system
- DO NOT modify this structure

platform_searches
- Stores Platform Selector Tool results
- Links to users via user_id
- Saves search history for each user

script_generations
- Stores Script Generator Tool outputs
- Links to users via user_id
- Allows users to access previously generated scripts

margin_calculations
- Stores Margin Calculator inputs and results
- Links to users via user_id
- Provides calculation history

vetter_checklists
- Stores Provider Vetter Checklist outputs
- Links to users via user_id
- Saves generated checklists for reference

All tables use InnoDB engine and utf8mb4 charset for proper emoji and 
international character support.

================================================================================
6. CONFIGURATION
================================================================================

DATABASE CONFIGURATION (config.php):
------------------------------------
define('USER_DB_HOST', 'localhost');
define('USER_DB_NAME', 'multicasting_db');
define('USER_DB_CHARSET', 'utf8mb4');
define('USER_DB_USER', 'db_user');
define('USER_DB_PASSWORD', 'db_password');

MULTI-USER SETTINGS (config.php):
----------------------------------
$adminuser = 'admin';          // Admin username
$adminpassword = 'adminpassword';  // Admin password
$sitename = 'Multicasting Deal Finder';  // Site name

ERROR LOGGING:
--------------
Error logs are written to:
- error.log (PHP errors)
- app.log (application-specific logs)

Ensure these files exist and are writable by the web server.

================================================================================
7. CDN RESOURCES USED
================================================================================

BOOTSTRAP 5.3.0
URL: https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css
URL: https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js
Purpose: Provides responsive grid system, styled components, and UI elements
Why: Industry-standard framework that makes the application mobile-friendly and 
      provides consistent styling across browsers

JQUERY 3.7.1
URL: https://code.jquery.com/jquery-3.7.1.min.js
Purpose: Simplifies JavaScript operations, AJAX calls, and DOM manipulation
Why: Makes code easier to write and debug, handles browser compatibility issues,
     provides simple AJAX methods for API communication

FONT AWESOME 6.4.0
URL: https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css
Purpose: Provides vector icons for the interface
Why: Professional-looking icons enhance user experience and make navigation intuitive
     Lightweight and doesn't require image files

NOTE: All CDN links are used WITHOUT SRI (Subresource Integrity) as requested.

================================================================================
8. CODE WALKTHROUGH
================================================================================

CONFIG.PHP - Core Functions
---------------------------

getDBConnection()
- Creates PDO database connection
- Sets error mode to exceptions for better error handling
- Disables emulated prepares for true prepared statements
- Returns PDO object or dies with error message

logMessage($level, $message, $context)
- Writes log entries to app.log
- Includes timestamp, level, message, and optional context
- Used throughout application for debugging

sanitizeInput($data)
- Recursively sanitizes input data
- Removes slashes and HTML special characters
- Prevents XSS attacks

safeStringOutput($data)
- Safely outputs data from API responses
- Handles strings, arrays, and objects
- Converts arrays to formatted strings
- Essential for preventing XSS from AI-generated content

getUserApiKey($userId)
- Retrieves user's OpenAI API key from database
- Returns null if not found
- Used before making API calls

updateUserApiKey($userId, $apiKey)
- Stores user's OpenAI API key in database
- Returns boolean success status
- Called from api_settings.php

callOpenAI($apiKey, $prompt, $maxTokens)
- Makes API call to OpenAI
- Uses gpt-4o-mini model for cost-effectiveness
- Handles errors and validates responses
- Returns array with 'content' or 'error' key
- Key parameters:
  * model: 'gpt-4o-mini'
  * temperature: 1 (as required)
  * max_completion_tokens: Configurable per request

JAVASCRIPT - app.js
-------------------

Utility Functions:
- showLoading(): Displays loading overlay
- hideLoading(): Hides loading overlay
- showResult(): Displays result card and scrolls to it
- hideResult(): Hides result card
- showError(): Shows error message to user
- copyToClipboard(): Copies text to clipboard with fallback
- formatContent(): Formats text with basic markdown to HTML

Form Handlers:
Each tool has its own form handler that:
1. Prevents default form submission
2. Validates input
3. Shows loading overlay
4. Makes AJAX POST request to corresponding API endpoint
5. Handles response (success or error)
6. Displays formatted results
7. Provides copy and reset functionality

AJAX Configuration:
- Timeout: 60 seconds (sufficient for API calls)
- Method: POST
- Data Type: JSON
- Error handling for network and server errors

API ENDPOINTS
-------------

All API endpoints follow the same pattern:
1. Check request method (POST only)
2. Validate and sanitize input
3. Check if user has API key configured
4. Construct appropriate prompt
5. Call OpenAI API via callOpenAI()
6. Handle API response
7. Save result to database
8. Return JSON response

generate_platforms.php
- Prompt includes niche and location
- Requests platform recommendations with explanations
- Token limit: 3000 (sufficient for detailed lists)

generate_script.php
- Prompt includes service type and optional platforms
- Requests three script versions (short, medium, long)
- Token limit: 3000 (allows for multiple scripts)

generate_checklist.php
- Prompt includes service category and specific needs
- Requests comprehensive vetting checklist
- Token limit: 3000 (detailed checklist with categories)

MARGIN CALCULATOR
-----------------
Note: This tool does NOT use AI - it's pure JavaScript calculation
- Calculates profit, margin percentage, and markup
- Generates projection table for different deal volumes
- All calculations happen client-side for instant results

================================================================================
9. DEBUGGING GUIDE
================================================================================

COMMON ISSUES AND SOLUTIONS:

1. "Database connection failed" error
   - Check config.php database credentials
   - Verify database exists in phpMyAdmin
   - Ensure database user has proper permissions
   - Check if MySQL service is running

2. "API key not configured" message
   - User needs to add OpenAI API key in API Settings
   - Verify api_settings.php is saving correctly
   - Check users table has user_claude_apikey column

3. API calls returning errors
   - Check error.log and app.log for details
   - Verify OpenAI API key is valid
   - Check if you have API credits remaining
   - Ensure curl extension is enabled in PHP
   - Test with a simple curl command to OpenAI API

4. Page showing blank or errors
   - Check PHP error logs
   - Verify all files uploaded correctly
   - Check file permissions (644 for files, 755 for directories)
   - Ensure PHP version is 8.0 or higher

5. Forms not submitting
   - Check browser console for JavaScript errors
   - Verify jQuery is loading (check Network tab)
   - Ensure app.js is loading after jQuery
   - Check if protect.php is blocking access

6. "Headers already sent" error
   - Check for whitespace before <?php tags
   - Ensure no output before header() calls in API files
   - Check for UTF-8 BOM in files

7. User authentication issues
   - Verify protect.php is working correctly
   - Check session configuration in config.php
   - Ensure login.php and logout.php are in place

DEBUGGING TOOLS:

Enable Error Display (for development only):
In config.php, change:
ini_set('display_errors', 0); to ini_set('display_errors', 1);

Check Logs:
- error.log: PHP errors
- app.log: Application-specific logs
- Browser console: JavaScript errors
- Network tab: AJAX request/response details

Test Database Connection:
Create a test file that calls getDBConnection() and outputs the result.

Test API Call:
Create a test file that calls callOpenAI() with a simple prompt.

================================================================================
10. EXTENDING THE APPLICATION
================================================================================

ADDING A NEW TOOL:

1. Create a new PHP page (e.g., new_tool.php)
   - Add require_once('protect.php'); at the top
   - Include header.php and footer.php
   - Create a form for user input
   - Add result display area

2. Create API endpoint (api/new_tool.php)
   - Add require_once(__DIR__ . '/../protect.php');
   - Validate input
   - Construct prompt
   - Call callOpenAI()
   - Return JSON response

3. Add JavaScript handler in app.js
   - Check for form existence
   - Handle form submission
   - Make AJAX call to new endpoint
   - Display results

4. Create database table if needed
   - Add CREATE TABLE statement to database.sql
   - Include user_id column
   - Add created_at timestamp

5. Update navigation in header.php
   - Add link to new tool

MODIFYING EXISTING TOOLS:

To change AI behavior:
- Edit the prompt in the corresponding api/ file
- Adjust max_completion_tokens if needed
- Test thoroughly with different inputs

To change UI:
- Edit the corresponding page file (e.g., platform_selector.php)
- Modify form fields
- Update validation in JavaScript
- Adjust result display format

To add features:
- Add new form fields
- Update API endpoint to handle new parameters
- Modify prompt to include new information
- Update database table if storing new data

ADDING ADMIN FEATURES:

1. Create admin_panel.php (protected)
2. Add user role checking in protect.php
3. Query database for all users or analytics
4. Display statistics or management options

================================================================================
11. SECURITY CONSIDERATIONS
================================================================================

INPUT VALIDATION:
- All user input is sanitized using sanitizeInput()
- API responses are safely output using safeStringOutput()
- Form data validated both client-side and server-side

SQL INJECTION PREVENTION:
- All database queries use prepared statements
- Parameters are properly bound
- No direct SQL concatenation with user input

XSS PREVENTION:
- htmlspecialchars() used on all output
- User-generated content escaped before display
- API responses sanitized before rendering

SESSION SECURITY:
- Session cookies set to HTTP-only
- Strict session mode enabled
- Session regeneration after login (handled by user-lib.php)

API KEY SECURITY:
- Keys stored in database, not in code
- Keys not exposed in JavaScript
- API calls made server-side only
- Users warned not to share keys

FILE PERMISSIONS:
- Files: 644 (read for all, write for owner)
- Directories: 755 (execute for all, write for owner)
- Config files: 600 (read/write for owner only) - recommended

PASSWORD SECURITY:
- Handled by existing user management system
- Should use password_hash() and password_verify()

HTTPS REQUIREMENT:
- Always use HTTPS in production
- API keys transmitted over secure connection
- Session cookies set to secure in production

RATE LIMITING:
- Consider implementing rate limiting for API endpoints
- Prevent abuse of OpenAI API
- Track usage per user in database

ERROR HANDLING:
- Generic error messages shown to users
- Detailed errors logged securely
- No sensitive information in error messages

================================================================================
SUPPORT AND UPDATES
================================================================================

For issues, questions, or suggestions:
- Check this documentation first
- Review the code comments in each file
- Check error logs for specific error messages
- Test with different browsers and clear cache
- Verify all requirements are met

Keep the application updated:
- Monitor OpenAI API changes and model updates
- Update CDN library versions periodically
- Check PHP version compatibility
- Backup database regularly

================================================================================
END OF TECHNICAL DOCUMENTATION
================================================================================