# Document Signing System for Garage Management

A complete PHP/MySQL system for creating, signing, and managing legal documents (warranties, service agreements, finance contracts, purchase agreements, etc.) with tablet-compatible digital signatures, PDF generation, email integration, and comprehensive audit trails.

## Features

✅ **Document Management**
- Create documents from templates
- Support for multiple document types (warranty, service agreement, finance agreement, purchase agreement, etc.)
- Dynamic PDF generation with timestamps
- Custom branding per garage
- Document archival and retrieval

✅ **Legal Digital Signatures**
- Tablet-friendly signature capture using HTML5 Canvas
- Legally binding signature timestamps
- Audit trail with IP logging
- Signature verification and validation
- Support for multiple signers (customer, admin, witness)

✅ **Email Integration**
- Automatic email to customer with signed PDF
- Notification to garage admin
- Email audit logging
- Customizable email templates with garage branding

✅ **Security Features**
- User authentication and role-based access
- CSRF token protection
- SQL injection prevention with prepared statements
- Secure file storage
- IP address logging and verification
- Cryptographic hashing of documents
- Session management with timeout

✅ **Admin Dashboard**
- Document statistics and analytics
- Recent documents overview
- Template management
- Settings management
- Audit log viewing

✅ **PDF Generation**
- Professional PDF output with signatures
- Multiple pages with audit trail
- Document verification codes
- Legally compliant formatting

## Installation

### Requirements
- PHP 7.4 or higher
- MySQL 5.7 or higher
- Web server (Apache, Nginx, etc.)
- PDO extension for PHP
- OpenSSL support

### Step 1: Upload Files
1. Create a folder on your web server (e.g., `/document-signing/`)
2. Upload all provided files maintaining the directory structure:
   ```
   document-signing/
   ├── config.php
   ├── database.sql
   ├── sign-document.php
   ├── admin-dashboard.php
   ├── login.php
   ├── register.php
   ├── Document.php
   ├── PDFGenerator.php
   ├── EmailHandler.php
   ├── assets/
   │   ├── css/
   │   │   └── style.css
   │   └── js/
   │       └── signature-pad.js
   ├── uploads/
   │   ├── pdfs/
   │   ├── signatures/
   │   └── templates/
   ├── TCPDF/
   └── PHPMailer/
   ```

### Step 2: Create Database
1. Open phpMyAdmin or your MySQL management tool
2. Create a new database: `document_signing`
3. Import the `database.sql` file into your database
4. Verify all tables are created

### Step 3: Install Dependencies
The system requires two PHP libraries. Download them:

**TCPDF** (PDF Generation)
- Download from: https://tcpdf.org/
- Extract to `/document-signing/TCPDF/`

**PHPMailer** (Email Handling)
- Download from: https://github.com/PHPMailer/PHPMailer
- Extract to `/document-signing/PHPMailer/`

Alternatively, use Composer:
```bash
composer require tecnickcom/tcpdf
composer require phpmailer/phpmailer
```

### Step 4: Configure Settings
Edit `config.php` and update:

```php
// Database
define('DB_HOST', 'localhost');
define('DB_USER', 'your_db_user');
define('DB_PASS', 'your_db_password');
define('DB_NAME', 'document_signing');

// Security
define('ENCRYPTION_KEY', 'change-this-to-a-long-random-string-32-chars');
define('HMAC_KEY', 'change-this-to-another-long-random-string');

// Base URL
define('BASE_URL', 'https://yourdomain.com/document-signing/');

// Email (SMTP)
define('SMTP_HOST', 'smtp.gmail.com');
define('SMTP_PORT', 587);
define('SMTP_USER', 'your-email@gmail.com');
define('SMTP_PASS', 'your-app-specific-password'); // Use app passwords for Gmail

// Garage Info
define('MAIL_FROM_EMAIL', 'noreply@yourgaragename.com');
define('MAIL_FROM_NAME', 'Your Garage Name');
```

### Step 5: Set Permissions
Make directories writable:
```bash
chmod 755 uploads/
chmod 755 uploads/pdfs/
chmod 755 uploads/signatures/
chmod 755 uploads/templates/
```

### Step 6: Create First User
1. Access your installation: `https://yourdomain.com/document-signing/`
2. Click "Register" and create your admin account
3. Log in with your credentials

## Usage

### Creating Documents

1. **Log in** to the admin dashboard
2. Click **"Create New Document"**
3. Fill in customer information and document details
4. Configure document fields specific to your garage
5. Choose document type (warranty, service agreement, etc.)
6. Submit to create the draft

### Signing Documents

1. Document is now in "pending signature" status
2. Click **"Sign Document"** tab
3. Enter signer details:
   - Signer name (customer or staff)
   - Email address
   - Role (customer/admin/witness)
4. **Draw signature** using touch or mouse on the signature pad
5. Click **"Sign & Finalize"**
6. System automatically:
   - Generates PDF with signatures
   - Records timestamp and IP
   - Sends emails to customer and admin
   - Archives the document

### Managing Documents

**View Documents:**
- Dashboard shows recent documents
- Filter by status (draft, pending, signed, archived)
- Download signed PDF
- Archive completed documents

**Audit Trail:**
- Access admin-dashboard.php → Audit Log
- View all document actions
- See IP addresses and timestamps
- Export audit data for compliance

### Email Customization

Edit email templates in `EmailHandler.php`:
- `getCustomerEmailTemplate()` - Customer email
- `getAdminEmailTemplate()` - Admin notification

Change branding in:
- `config.php` - MAIL_FROM_EMAIL, MAIL_FROM_NAME
- `User.garage_name` table - per-garage customization

## Security Considerations

### For Production:

1. **Enable HTTPS** - Set `REQUIRE_HTTPS = true` in config.php
2. **Change Encryption Keys** - Generate random strings for ENCRYPTION_KEY and HMAC_KEY
3. **Database Backups** - Regular automated backups
4. **Password Hashing** - Use `password_hash()` for user passwords
5. **File Permissions** - Restrict access to uploads directory
6. **Rate Limiting** - Implement to prevent abuse
7. **SSL Certificate** - Install valid SSL certificate
8. **Firewall** - Whitelist IP addresses if possible

### GDPR Compliance:

- Documents are encrypted and stored securely
- Customer data can be exported via audit log
- Implement data retention policy
- Allow users to request data deletion
- Maintain audit trails for 3-7 years

### Signature Legality:

This system captures legally binding signatures with:
- Timestamps (authentication)
- IP logging (non-repudiation)
- Audit trail (integrity)
- Signature hash verification (verification)

**Note:** For maximum legal validity, consider implementing:
- Digital certificates (eIDAS compliance)
- Third-party e-signature service integration (DocuSign, Adobe Sign)
- Legal review of terms and conditions

## API Reference

### Document Class

```php
$doc = new Document($pdo);

// Create document
$result = $doc->create($user_id, $template_id, $type, $customer_data, $fields);

// Get document
$document = $doc->get($document_id, $user_id);

// Add signature
$doc->addSignature($document_id, $signature_data, $signer_name, $signer_email, $role);

// Get statistics
$stats = $doc->getStats($user_id);
```

### PDFGenerator Class

```php
$pdf = new PDFGenerator($pdo);

// Generate PDF
$result = $pdf->generateFromDocument($document_id, $include_signatures = true);

// Download
$pdf->downloadPDF($filepath, $filename);
```

### EmailHandler Class

```php
$email = new EmailHandler($pdo);

// Send document
$result = $email->sendSignedDocument($document_id, $pdf_path);

// Get history
$history = $email->getEmailHistory($document_id);
```

## Database Structure

### Main Tables:

- **users** - Admin/garage staff accounts
- **documents** - Document records with metadata
- **signatures** - Digital signatures with timestamps
- **document_templates** - Reusable templates
- **email_log** - Email sending history
- **audit_log** - Complete action audit trail

## Troubleshooting

### Common Issues:

**1. Email not sending**
- Verify SMTP credentials in config.php
- Check Gmail "Less secure apps" setting or use app-specific password
- Look for errors in error_log

**2. PDF generation fails**
- Ensure TCPDF is properly installed
- Check file permissions on uploads/ directory
- Verify temp directory is writable

**3. Signature not displaying**
- Ensure signature data is valid base64
- Check browser console for JavaScript errors
- Verify canvas size is set correctly

**4. Database connection error**
- Verify database credentials in config.php
- Check database server is running
- Ensure database exists and is accessible

## Support & Customization

### Common Customizations:

1. **Custom Document Fields** - Edit the form in `sign-document.php`
2. **Email Templates** - Modify `EmailHandler.php`
3. **PDF Styling** - Edit `PDFGenerator.php`
4. **Branding** - Add garage logo and colors
5. **Additional Signatures** - Modify signature section logic

## License

This system is provided as-is for your garage business use.

## Important Notes

- **Backup your data regularly**
- **Test thoroughly** before production use
- **Consult legal counsel** on document requirements
- **Review email templates** for accuracy
- **Keep PHP and libraries updated** for security

---

**Version:** 1.0  
**Last Updated:** 2026-05-28
