# Installation Guide - Car Showroom Management System

Complete step-by-step installation guide for the Car Showroom Management System.

## Table of Contents
1. [System Requirements](#system-requirements)
2. [Pre-Installation Checklist](#pre-installation-checklist)
3. [Installation Steps](#installation-steps)
4. [Configuration](#configuration)
5. [Testing](#testing)
6. [Post-Installation](#post-installation)
7. [Troubleshooting](#troubleshooting)

---

## System Requirements

### Server Requirements
- **Web Server**: Apache 2.4+ or Nginx 1.18+
- **PHP**: 8.2 or higher
- **Database**: MySQL 8.0+ or MariaDB 10.5+
- **SSL Certificate**: Required for production (Let's Encrypt recommended)

### PHP Extensions Required
```
- mysqli
- curl
- json
- mbstring
- openssl
- fileinfo
- gd (for image processing)
- zip (for backups)
```

### Recommended Server Specifications
- **RAM**: Minimum 2GB, Recommended 4GB+
- **Storage**: Minimum 10GB free space
- **CPU**: 2+ cores recommended

---

## Pre-Installation Checklist

- [ ] Web server installed and running
- [ ] PHP 8.2+ installed with required extensions
- [ ] MySQL 8.0+ installed and running
- [ ] Domain/subdomain configured (for production)
- [ ] SSL certificate installed (for production)
- [ ] FTP/SSH access to server
- [ ] Database credentials ready
- [ ] M-Pesa Daraja API credentials (optional, can configure later)
- [ ] SMS API credentials (optional, can configure later)
- [ ] SMTP email credentials (optional, can configure later)

---

## Installation Steps

### Step 1: Download and Extract Files

#### Option A: Using Git (Recommended)
```bash
cd /var/www/html/
# or for XAMPP: cd C:/xampp/htdocs/

git clone <repository-url> showroom
cd showroom
```

#### Option B: Manual Upload
1. Download the ZIP file
2. Extract to your web server directory
3. Rename folder to `showroom`

### Step 2: Set File Permissions (Linux/Mac)

```bash
cd /var/www/html/showroom

# Set directory permissions
find . -type d -exec chmod 755 {} \;

# Set file permissions
find . -type f -exec chmod 644 {} \;

# Make uploads directory writable
chmod -R 775 uploads/
chown -R www-data:www-data uploads/

# Protect config directory
chmod 750 config/
```

#### For Windows (XAMPP)
- Right-click `uploads` folder → Properties → Security
- Give "Full Control" to "Users" group

### Step 3: Create Database

#### Option A: Using phpMyAdmin
1. Open phpMyAdmin: `http://localhost/phpmyadmin`
2. Click "New" to create database
3. Database name: `car_showroom`
4. Collation: `utf8mb4_unicode_ci`
5. Click "Create"
6. Select the database
7. Click "Import" tab
8. Choose file: `database/schema.sql`
9. Click "Go"

#### Option B: Using MySQL Command Line
```bash
# Login to MySQL
mysql -u root -p

# Create database
CREATE DATABASE car_showroom CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

# Exit MySQL
exit;

# Import schema
mysql -u root -p car_showroom < database/schema.sql
```

#### Verify Database Installation
```sql
USE car_showroom;
SHOW TABLES;
-- Should show 12 tables

SELECT * FROM users;
-- Should show default admin user
```

### Step 4: Configure Database Connection

Edit `config/config.php`:

```php
// Database Configuration
define('DB_HOST', 'localhost');        // Usually 'localhost'
define('DB_USER', 'root');             // Your MySQL username
define('DB_PASS', '');                 // Your MySQL password
define('DB_NAME', 'car_showroom');     // Database name
define('DB_CHARSET', 'utf8mb4');
```

**For Production:**
```php
define('DB_HOST', 'localhost');
define('DB_USER', 'showroom_user');    // Create dedicated user
define('DB_PASS', 'strong_password');  // Use strong password
define('DB_NAME', 'car_showroom');
```

### Step 5: Configure Application URLs

Edit `config/config.php`:

**For Local Development (XAMPP/WAMP):**
```php
define('APP_URL', 'http://localhost/showroom');
define('ADMIN_URL', APP_URL . '/admin');
define('CUSTOMER_URL', APP_URL . '/customer');
define('API_URL', APP_URL . '/api');
```

**For Production:**
```php
define('APP_URL', 'https://yourdomain.com');
define('ADMIN_URL', APP_URL . '/admin');
define('CUSTOMER_URL', APP_URL . '/customer');
define('API_URL', APP_URL . '/api');
```

### Step 6: Create Upload Directories

```bash
# Create directories
mkdir -p uploads/cars
mkdir -p uploads/customers
mkdir -p uploads/documents
mkdir -p uploads/temp

# Set permissions (Linux/Mac)
chmod -R 775 uploads/
chown -R www-data:www-data uploads/
```

### Step 7: Install PHPMailer

#### Option A: Manual Installation
1. Download PHPMailer from: https://github.com/PHPMailer/PHPMailer
2. Extract to `vendor/PHPMailer/`
3. Ensure these files exist:
   - `vendor/PHPMailer/PHPMailer.php`
   - `vendor/PHPMailer/SMTP.php`
   - `vendor/PHPMailer/Exception.php`

#### Option B: Using Composer (Recommended)
```bash
cd /var/www/html/showroom
composer require phpmailer/phpmailer
```

### Step 8: Test Installation

1. Open browser and navigate to:
   ```
   http://localhost/showroom/admin/login.php
   ```

2. Login with default credentials:
   - **Username**: `admin`
   - **Password**: `admin123`

3. If login successful, installation is complete!

---

## Configuration

### M-Pesa Configuration

#### Step 1: Get M-Pesa Credentials
1. Visit: https://developer.safaricom.co.ke/
2. Register/Login
3. Create new app
4. Get credentials:
   - Consumer Key
   - Consumer Secret
   - Shortcode (Paybill/Till)
   - Passkey

#### Step 2: Configure in System

**Option A: Via Admin Panel (Recommended)**
1. Login to admin panel
2. Go to Settings → Integrations
3. Enter M-Pesa credentials
4. Save

**Option B: Edit config.php**
```php
// M-Pesa Configuration
define('MPESA_CONSUMER_KEY', 'your_consumer_key_here');
define('MPESA_CONSUMER_SECRET', 'your_consumer_secret_here');
define('MPESA_SHORTCODE', '174379');  // Your paybill/till number
define('MPESA_PASSKEY', 'your_passkey_here');
define('MPESA_ENVIRONMENT', 'sandbox'); // 'sandbox' or 'production'
```

#### Step 3: Register Callback URL
1. In Daraja portal, register callback URL:
   ```
   https://yourdomain.com/showroom/api/mpesa_callback.php
   ```
2. Or use the system to auto-register:
   - Go to Settings → M-Pesa
   - Click "Register URLs"

#### Step 4: Configure IP Whitelist
Edit `config/config.php`:
```php
define('MPESA_ALLOWED_IPS', [
    '196.201.214.200',  // Safaricom IP 1
    '196.201.214.206',  // Safaricom IP 2
    '196.201.213.114',  // Safaricom IP 3
    '127.0.0.1',        // Localhost (for testing)
    'YOUR_SERVER_IP'    // Your server IP
]);
```

### SMS Configuration (textsms.co.ke)

#### Step 1: Get SMS Credentials
1. Visit: https://textsms.co.ke/
2. Register account
3. Purchase SMS credits
4. Get API credentials from dashboard

#### Step 2: Configure in System
```php
// SMS Configuration
define('SMS_API_KEY', 'your_api_key');
define('SMS_PARTNER_ID', 'your_partner_id');
define('SMS_SENDER_ID', 'SHOWROOM');  // Your sender name
define('SMS_API_URL', 'https://sms.textsms.co.ke/api/services/sendsms');
define('SMS_ENABLED', true);
```

### Email Configuration

#### For Gmail:
1. Enable 2-Factor Authentication
2. Generate App Password:
   - Google Account → Security → App Passwords
   - Select "Mail" and "Other"
   - Copy generated password

3. Configure:
```php
define('SMTP_HOST', 'smtp.gmail.com');
define('SMTP_PORT', 587);
define('SMTP_USERNAME', 'your_email@gmail.com');
define('SMTP_PASSWORD', 'your_app_password');
define('SMTP_ENCRYPTION', 'tls');
define('SMTP_FROM_EMAIL', 'your_email@gmail.com');
define('SMTP_FROM_NAME', 'Car Showroom');
define('EMAIL_ENABLED', true);
```

#### For Other SMTP Providers:
```php
// Example for custom SMTP
define('SMTP_HOST', 'mail.yourdomain.com');
define('SMTP_PORT', 465);
define('SMTP_USERNAME', 'noreply@yourdomain.com');
define('SMTP_PASSWORD', 'your_password');
define('SMTP_ENCRYPTION', 'ssl');
```

---

## Testing

### Test Database Connection
Create `test_db.php` in root:
```php
<?php
require_once 'config/config.php';
$db = Database::getInstance();
echo "Database connection successful!";
?>
```
Visit: `http://localhost/showroom/test_db.php`

### Test M-Pesa Integration
1. Login to admin
2. Go to Settings → M-Pesa
3. Click "Test Connection"
4. Should show "Connection Successful"

### Test SMS
1. Go to Notifications
2. Send test SMS to your number
3. Check if received

### Test Email
1. Go to Notifications
2. Send test email
3. Check inbox/spam

---

## Post-Installation

### Security Checklist

1. **Change Default Password**
   ```
   Login → Profile → Change Password
   ```

2. **Create Database User (Production)**
   ```sql
   CREATE USER 'showroom_user'@'localhost' IDENTIFIED BY 'strong_password';
   GRANT ALL PRIVILEGES ON car_showroom.* TO 'showroom_user'@'localhost';
   FLUSH PRIVILEGES;
   ```

3. **Enable HTTPS**
   - Install SSL certificate
   - Update APP_URL to https://
   - Uncomment HTTPS redirect in .htaccess

4. **Secure File Permissions**
   ```bash
   chmod 640 config/config.php
   chmod 640 config/notification_templates.php
   ```

5. **Disable Error Display (Production)**
   ```php
   // In config.php
   define('DEBUG_MODE', false);
   ini_set('display_errors', 0);
   ```

6. **Set Up Backups**
   - Database: Daily automated backups
   - Files: Weekly backups
   - Store offsite

7. **Configure Firewall**
   - Allow ports: 80, 443
   - Restrict MySQL port (3306) to localhost only

8. **Enable Logging**
   ```php
   ini_set('log_errors', 1);
   ini_set('error_log', '/path/to/php-error.log');
   ```

### Recommended Settings

1. **Company Information**
   - Go to Settings → General
   - Update company name, address, phone, email

2. **Notification Templates**
   - Review templates in `config/notification_templates.php`
   - Customize messages as needed

3. **Create Additional Users**
   - Go to Users → Add New
   - Create manager/staff accounts

4. **Set Up Cron Jobs** (for automated tasks)
   ```bash
   # Send payment reminders daily at 9 AM
   0 9 * * * php /path/to/showroom/cron/send_reminders.php
   
   # Update overdue status daily at midnight
   0 0 * * * php /path/to/showroom/cron/update_overdue.php
   ```

---

## Troubleshooting

### Issue: Cannot connect to database
**Solution:**
- Verify MySQL is running
- Check credentials in config.php
- Ensure database exists
- Check user permissions

### Issue: M-Pesa callback not working
**Solution:**
- Verify callback URL is registered
- Check IP whitelist
- Ensure SSL is enabled
- Check error logs

### Issue: SMS not sending
**Solution:**
- Verify API credentials
- Check SMS balance
- Test API directly
- Check phone number format (254...)

### Issue: Email not sending
**Solution:**
- Verify SMTP credentials
- Check firewall/port blocking
- For Gmail, use App Password
- Check spam folder

### Issue: File upload fails
**Solution:**
- Check directory permissions
- Verify upload_max_filesize in php.ini
- Check available disk space

### Issue: Session timeout too fast
**Solution:**
```php
// In config.php, increase session lifetime
define('SESSION_LIFETIME', 7200); // 2 hours
```

### Issue: 500 Internal Server Error
**Solution:**
- Check PHP error log
- Verify .htaccess syntax
- Check file permissions
- Enable error display temporarily

---

## Support

For additional help:
1. Check error logs
2. Review README.md
3. Check database logs
4. Review M-Pesa transaction logs

---

## Next Steps

After successful installation:
1. ✅ Change default admin password
2. ✅ Configure company information
3. ✅ Set up M-Pesa integration
4. ✅ Configure SMS/Email
5. ✅ Add cars to inventory
6. ✅ Create customer accounts
7. ✅ Test hire purchase flow
8. ✅ Test payment processing
9. ✅ Set up automated backups
10. ✅ Train staff on system usage

---

**Installation Complete! 🎉**

Your Car Showroom Management System is now ready to use.
