# PDF Sign & Fill - v1.1.0 (Freemius Ready)

A professional WordPress plugin for collecting digital signatures on fillable PDFs with secure document storage. Now integrated with Freemius SDK for licensing, automatic updates, and premium support.

## Version 1.1.0 Highlights

🎉 **Freemius Integration** - Modern licensing system with automatic updates for premium users  
🔓 **Soft Activation** - Plugin works 100% without license activation  
🚀 **All Features Unlocked** - Signature collection, PDF generation, and storage work for everyone  
💎 **Premium Benefits** - Automatic updates and priority support for premium license holders

## Core Features

- ✅ Upload fillable PDF templates with automatic field detection
- ✅ Digital signature capture using HTML5 Canvas (mobile responsive)
- ✅ TCPDF-based PDF generation with signature embedding
- ✅ Secure server storage of signed documents
- ✅ Email notifications with PDF attachments
- ✅ Comprehensive admin dashboard and audit trail
- ✅ Works for non-logged-in users (public forms)
- ✅ Fully responsive design with PDF.js rendering
- ✅ AJAX form submission with validation
- ✅ IP tracking and user agent logging

## Installation

### Method 1: Manual Installation

1. Copy the `pdf-sign-fill` folder to your WordPress plugins directory:
   ```
   wp-content/plugins/pdf-sign-fill/
   ```

2. Go to WordPress Admin > Plugins
3. Find "PDF Sign & Fill" and click "Activate"
4. Navigate to "Signed Agreements" menu in admin sidebar

### Method 2: Upload via WordPress Admin

1. Go to WordPress Admin > Plugins > Add New
2. Click "Upload Plugin" button
3. Choose the `pdf-sign-fill.zip` file
4. Click "Install Now" and then "Activate"

## Freemius Integration (v1.1.0+)

The plugin now uses Freemius SDK for licensing and updates. **Activation is optional** - all core features work without a license.

### What Works Without License?
- ✅ All PDF signature collection
- ✅ All PDF generation and storage
- ✅ All email notifications
- ✅ All admin features
- ✅ All templates and field detection

### What Requires Premium License?
- 🔄 Automatic plugin updates
- 💬 Priority email support

### License Management
1. Go to Admin > Signed Agreements > License
2. View your current plan (Free/Trial/Premium)
3. Click "Upgrade to Premium" to purchase
4. Click "Manage License" to view account details

No purchase code entry needed - Freemius handles everything through your WordPress.org account.

## Usage

### Step 1: Upload a PDF Template

1. Go to WordPress Admin > Signed Agreements > Templates
2. Click "Add New Template" button
3. Upload your fillable PDF file
4. System automatically detects form fields
5. Configure field labels and options
6. Save template

### Step 2: Add Form to a Page

1. Create or edit a WordPress page
2. Add the following shortcode:
   ```
   [pdf_sign_fill agreement_type="purchase-agreement"]
   ```

### Shortcode Parameters

```
[pdf_sign_fill 
    agreement_type="purchase-agreement"
    template_id="123"]
```

**Parameters:**
- `agreement_type` (required) - Internal identifier for the agreement type
- `template_id` (optional) - Specific PDF template ID to use

### Alternative Shortcode

For more control over the form display:
```
[psf_signature_form 
    agreement_type="service-agreement"]
```

### Examples

Basic usage:
```
[pdf_sign_fill agreement_type="purchase-agreement"]
```

Specific template:
```
[pdf_sign_fill agreement_type="nda" template_id="456"]
```

## Admin Panel

After activation, you'll see "Signed Agreements" menu in the WordPress admin sidebar.

### Admin Pages:
- **Overview** - Dashboard with signed documents list
- **Templates** - Upload and manage PDF templates
- **Settings** - Configure email notifications and storage options
- **License** - Manage Freemius license (v1.1.0+)

### Features:
- View all signed agreements with pagination
- Download individual PDFs
- View detailed form data in JSON format
- Delete agreements
- Generate audit trail certificates
- Search and filter documents
- Export data

### Accessing Admin Panel:
1. Go to WordPress Admin Dashboard
2. Click "Signed Agreements" in the left sidebar
3. View, download, or manage signed documents

## File Storage

Signed PDFs are stored in:
```
wp-content/uploads/psf-signed-agreements/
```

PDF templates are stored in:
```
wp-content/uploads/psf-templates/
```

**Security:**
- Directories have `.htaccess` files to prevent directory listing
- Files accessible only through WordPress authentication
- Each filename includes timestamp for uniqueness

**Filename Format:**
```
agreement-type_customer-name_timestamp.pdf
Example: purchase-agreement_john-doe_1737561234.pdf
```

## Email Notifications

Both admin and customer receive email notifications with signed PDF attached.

### Admin Notification
- Sent to site admin email (from Settings > General)
- Includes customer name, email, phone, and agreement type
- PDF attachment of signed document
- Customizable subject and message

### Customer Confirmation
- Sent to customer's email address provided in form
- Includes copy of signed PDF as attachment
- Thank you message and next steps
- Professional formatting

### Customizing Emails
Go to Admin > Signed Agreements > Settings to customize:
- Email subject lines
- Email body text
- From name and email address
- CC/BCC recipients

## Database

The plugin creates table: `wp_psf_signed_docs`

**Table Structure:**
- `id` - Auto-increment primary key
- `customer_name` - Customer's full name (VARCHAR 255)
- `customer_email` - Customer's email (VARCHAR 255)
- `customer_phone` - Customer's phone number (VARCHAR 50)
- `agreement_type` - Type of agreement (VARCHAR 100)
- `stock_number` - Optional stock/reference number (VARCHAR 100)
- `form_data` - JSON with all form fields (LONGTEXT)
- `file_path` - Relative path to PDF file (VARCHAR 500)
- `ip_address` - Customer's IP address (VARCHAR 45)
- `user_agent` - Customer's browser/device info (TEXT)
- `signed_at` - Timestamp when document was signed (DATETIME)

**Indexes:**
- Primary key on `id`
- Index on `customer_email` for quick lookups
- Index on `agreement_type` for filtering
- Index on `signed_at` for sorting

## Customization

### Modifying Form Fields

The form displays fields automatically detected from your uploaded PDF template. To customize:

1. Go to Admin > Signed Agreements > Templates
2. Click "Edit Labels" on any template
3. Rename field labels as needed
4. Delete unwanted fields
5. Save changes

### Customizing PDF Output

PDF generation uses TCPDF library with embedded signatures. To customize the output, you can:

1. Modify the PDF template before uploading (use Adobe Acrobat or similar)
2. Adjust field positions and sizes in the source PDF
3. Add custom styling through plugin CSS filters

### Adding Custom CSS

Add to your theme's `style.css` or use a custom CSS plugin:

```css
/* Customize signature form container */
.psf-signature-form-container {
    max-width: 800px;
    margin: 0 auto;
}

/* Customize signature pad */
.signature-pad canvas {
    border: 2px solid #007bff;
    border-radius: 8px;
}

/* Customize submit button */
.psf-submit-btn {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 15px 40px;
    font-size: 18px;
}
```

### Developer Hooks

The plugin provides hooks for developers:

**Actions:**
- `psf_after_signature_saved` - Fires after document is saved
- `psf_after_email_sent` - Fires after emails are sent
- `psf_template_uploaded` - Fires after template is uploaded

**Filters:**
- `psf_email_subject` - Modify email subject line
- `psf_email_message` - Modify email body content
- `psf_pdf_filename` - Customize PDF filename format

## Troubleshooting

### Freemius Errors (v1.1.0+)
**Issue**: "Freemius SDK not found" warning in admin
**Solution**: 
1. Verify `/freemius/` folder exists in plugin directory
2. Check that `freemius/start.php` file is present
3. Re-upload plugin files if missing

### Form Not Appearing
**Issue**: Shortcode displays as text instead of form
**Solutions**:
1. Verify plugin is activated (Admin > Plugins)
2. Check shortcode syntax: `[pdf_sign_fill agreement_type="test"]`
3. Clear cache if using caching plugin (WP Super Cache, etc.)
4. Ensure no JavaScript errors in browser console (F12)

### Signature Pad Not Working
**Issue**: Cannot draw signature or canvas is blank
**Solutions**:
1. Check browser console (F12) for JavaScript errors
2. Ensure jQuery is loaded (theme compatibility issue)
3. Try on different browser/device to isolate issue
4. Check if theme CSS conflicts with canvas element
5. Test with default WordPress theme to rule out theme issues

### PDF Not Generating or Downloading
**Issue**: Form submits but no PDF is created
**Solutions**:
1. Check PHP error logs in hosting control panel
2. Verify TCPDF library is present in `/vendor/tcpdf/`
3. Check file permissions on uploads directory (755 or 775)
4. Increase PHP memory limit (256MB recommended)
5. Check PHP max_execution_time (60 seconds minimum)

### Emails Not Sending
**Issue**: Form submits successfully but no emails received
**Solutions**:
1. Check spam/junk folders first
2. Verify WordPress email settings (Settings > General)
3. Install SMTP plugin (WP Mail SMTP recommended)
4. Test email functionality with standard WordPress emails
5. Check hosting email sending limits
6. Review server mail logs

### File Permission Issues
**Issue**: "Failed to save PDF" error
**Solutions**:
1. Ensure `wp-content/uploads/` is writable (chmod 755 or 775)
2. Check ownership (should match web server user)
3. Create directories manually if automatic creation fails:
   - `wp-content/uploads/psf-signed-agreements/`
   - `wp-content/uploads/psf-templates/`
4. Contact hosting provider for permission assistance

### Template Upload Fails
**Issue**: Cannot upload PDF template in admin
**Solutions**:
1. Check file size doesn't exceed upload_max_filesize (php.ini)
2. Verify PDF is valid and not corrupted
3. Ensure file is actual PDF (not renamed DOC/DOCX)
4. Check available disk space on server
5. Review PHP upload settings (max_file_uploads, post_max_size)

### Mobile Signature Issues (Fixed in v1.0.1)
**Issue**: Signature canvas not working on mobile devices  
**Status**: Fixed in version 1.0.1 (Mobile Fix)
**Solution**: Update to latest version

### Database Table Not Created
**Issue**: Plugin activated but admin page shows errors
**Solutions**:
1. Deactivate and reactivate plugin
2. Check database user has CREATE TABLE permission
3. Manually run SQL from `/includes/database-schema.sql`
4. Check PHP error logs for database errors

### Still Having Issues?

Enable WordPress debug mode to see detailed errors:

1. Edit `wp-config.php`
2. Add before "That's all, stop editing!":
   ```php
   define('WP_DEBUG', true);
   define('WP_DEBUG_LOG', true);
   define('WP_DEBUG_DISPLAY', false);
   ```
3. Check `/wp-content/debug.log` for errors
4. Review browser console (F12) for JavaScript errors
5. Check server error logs in hosting control panel

## Premium Support

Premium license holders get priority email support with faster response times.

**Free Plan Support:**
- Community support via WordPress.org forums
- Documentation and troubleshooting guides
- Bug reports via GitHub (if available)

**Premium Support Includes:**
- Priority email support (24-48 hour response)
- Direct developer assistance
- Custom implementation guidance
- Early access to new features

**To Upgrade:**
1. Go to Admin > Signed Agreements > License
2. Click "Upgrade to Premium"
3. Complete checkout through Freemius

## Technical Requirements

- **WordPress**: 5.0 or higher
- **PHP**: 7.4 or higher (8.0+ recommended)
- **MySQL**: 5.6 or higher
- **PHP Extensions**: GD or Imagick, mbstring, json
- **Memory**: 256MB minimum (512MB recommended)
- **Upload Size**: 10MB minimum for PDF templates

## Changelog

### Version 1.1.0 (February 2026) - Freemius Ready
- ✅ **NEW**: Integrated Freemius SDK for modern licensing system
- ✅ **NEW**: Automatic plugin updates for premium users
- ✅ **NEW**: Premium support channel for license holders
- ✅ **IMPROVED**: License management page (no more manual activation codes)
- ✅ **REMOVED**: Legacy custom license server integration
- ✅ **REMOVED**: Deprecated class-psf-license.php file
- ⚙️ **TECHNICAL**: Soft activation model - all features work without license
- ⚙️ **TECHNICAL**: Graceful fallback if Freemius SDK not loaded
- 📚 **DOCS**: Updated PLUGIN-ARCHITECTURE.md with Freemius integration
- 📚 **DOCS**: Added FREEMIUS-MIGRATION.md guide

### Version 1.0.1 (January 2026) - Mobile Fix
- 🐛 **FIXED**: Signature canvas rendering on mobile devices
- 🐛 **FIXED**: Touch event handling for iOS Safari
- 🐛 **FIXED**: Responsive PDF preview on small screens
- ⚙️ **IMPROVED**: Mobile-first CSS for signature form
- ⚙️ **IMPROVED**: Touch-friendly button sizes

### Version 1.0.0 (January 2026) - Initial Release
- 🎉 First public release
- ✅ Upload fillable PDF templates
- ✅ Automatic field detection from PDFs
- ✅ Digital signature capture with HTML5 Canvas
- ✅ TCPDF-based PDF generation with signatures
- ✅ Email notifications to admin and customer
- ✅ Secure document storage
- ✅ Comprehensive admin dashboard
- ✅ Audit trail certificate generation
- ✅ Support for non-logged-in users
- ✅ Mobile responsive design
- ✅ AJAX form submission

## Security & Privacy

- **Data Storage**: All signed documents stored securely on your WordPress server
- **No External Services**: No data sent to third parties (except Freemius for license validation)
- **Access Control**: Admin-only access to stored documents
- **IP Logging**: Records IP address and user agent for audit trail
- **File Security**: `.htaccess` protection on upload directories
- **Nonce Verification**: All AJAX requests protected with WordPress nonces
- **SQL Injection**: All database queries use prepared statements

## License

GPL v2 or later - https://www.gnu.org/licenses/gpl-2.0.html

This plugin is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation.

## Credits & Dependencies

**Core Technologies:**
- **WordPress** - Content management system
- **TCPDF** - PHP PDF generation library
- **FPDI** - PDF template parsing
- **PDF.js** - JavaScript PDF rendering
- **Freemius SDK** - Licensing and update system (v1.1.0+)

**JavaScript Libraries:**
- **jQuery** - DOM manipulation
- **Signature Pad** - HTML5 signature capture (if used)

**Icons & Assets:**
- Font Awesome (if used for admin icons)

## Developer Resources

**File Structure:**
```
pdf-sign-fill/
├── admin/                  # Admin pages and functionality
├── assets/                 # CSS, JS, images
├── freemius/              # Freemius SDK (v1.1.0+)
├── includes/              # Core PHP classes
├── templates/             # Front-end form templates
├── vendor/                # Third-party libraries (TCPDF, FPDI)
├── pdf-sign-fill.php     # Main plugin file
└── README.md             # This file
```

**Key Files:**
- `pdf-sign-fill.php` - Main plugin bootstrap with Freemius integration
- `includes/class-audit-certificate.php` - Audit trail generation
- `admin/psf-license-page.php` - Freemius license management UI
- `assets/js/pdf-interactive.js` - Front-end signature form
- `assets/js/admin.js` - Admin template management

**Documentation:**
- `PLUGIN-ARCHITECTURE.md` - Complete technical architecture
- `FREEMIUS-MIGRATION.md` - Migration guide from legacy system

---

**Made with ❤️ by PDF Sign & Fill Team**
