# Subscription Management System - Setup Guide

Complete installation and configuration guide for the multi-tenant subscription management system.

---

## 📋 Table of Contents

1. [System Overview](#system-overview)
2. [Prerequisites](#prerequisites)
3. [Installation Steps](#installation-steps)
4. [Configuration](#configuration)
5. [Testing](#testing)
6. [Usage Examples](#usage-examples)
7. [Troubleshooting](#troubleshooting)
8. [Maintenance](#maintenance)

---

## 🎯 System Overview

### What It Does
- **Validates subscriptions** against a master database on every dashboard load
- **Automatically blocks access** when subscriptions expire
- **Shows alerts** 7 days before expiration
- **Grace period support** (3 days after expiry)
- **1-hour caching** for optimal performance
- **Audit trail** of all subscription changes

### Architecture
```
┌─────────────────────────────────────────┐
│   Client Browsers (Subdomains)         │
│   restaurant.example.com                │
│   pharmacy.example.com                  │
└──────────────┬──────────────────────────┘
               │
               ↓
┌─────────────────────────────────────────┐
│   POS Application                       │
│   ┌──────────────────────────────────┐  │
│   │ Subscription_validator Library   │  │
│   │ (1-hour cache)                   │  │
│   └─────────────┬────────────────────┘  │
└─────────────────┼───────────────────────┘
                  │
        ┌─────────┴──────────┐
        │                    │
        ↓                    ↓
┌──────────────┐    ┌──────────────────┐
│ Tenant DBs   │    │ Master DB        │
│ webPos_rest  │    │ master_subs      │
│ webPos_pharm │    │ - client_subs    │
│ webPos_groc  │    │ - sub_history    │
└──────────────┘    └──────────────────┘
```

---

## ✅ Prerequisites

- **PHP**: 7.0 or higher
- **MySQL**: 5.6 or higher
- **CodeIgniter**: 3.x (already installed)
- **Apache/Nginx**: Web server with mod_rewrite enabled
- **XAMPP/WAMP**: For local development

---

## 🚀 Installation Steps

### Step 1: Import Master Database

```bash
# Navigate to MySQL
cd C:\xampp\mysql\bin

# Import the master database
mysql -u root -p < C:\xampp\htdocs\pos\database\master_subscription_db.sql

# Verify database creation
mysql -u root -p -e "SHOW DATABASES LIKE 'master_subscriptions';"

# Verify tables
mysql -u root -p master_subscriptions -e "SHOW TABLES;"
```

**Expected Output:**
```
+----------------------------------+
| Tables_in_master_subscriptions   |
+----------------------------------+
| client_subscriptions             |
| subscription_alerts              |
| subscription_history             |
| view_active_subscriptions        |
+----------------------------------+
```

### Step 2: Verify Files Created

All files should already be in place. Verify their existence:

```
✓ database/master_subscription_db.sql
✓ application/config/master_database.php
✓ application/config/subscription.php
✓ application/libraries/Subscription_validator.php
✓ application/hooks/Subscription_check.php
✓ application/controllers/Subscription.php
✓ application/views/comman/subscription_alert.php
✓ application/views/subscription_expired.php
```

### Step 3: Configuration Already Applied

The following configurations have been automatically applied:

- ✅ `application/config/config.php` → hooks enabled
- ✅ `application/config/hooks.php` → subscription check registered
- ✅ `application/views/dashboard.php` → alert component included

---

## ⚙️ Configuration

### 1. Update Master Database Credentials

Edit `application/config/master_database.php`:

```php
$master_db = array(
    'hostname' => 'localhost',        // Your MySQL host
    'username' => 'root',              // Your MySQL username
    'password' => '',                  // Your MySQL password
    'database' => 'master_subscriptions',
    // ... other settings
);
```

### 2. Customize Support Information

Edit `application/config/subscription.php`:

```php
// Update with your actual support contact
$config['subscription_support_email'] = 'mahfuzcmt@gmail.com';
$config['subscription_support_phone'] = '+8801975585960';

// Adjust cache duration if needed (default: 1 hour)
$config['subscription_cache_duration'] = 3600; // seconds

// Alert thresholds
$config['subscription_alert_warning'] = 7;  // Show warning 7 days before
$config['subscription_alert_critical'] = 3; // Critical at 3 days
```

### 3. Verify Sample Data

Check if sample subscriptions were imported:

```sql
SELECT tenant_name, company_name, end_date, is_active
FROM master_subscriptions.client_subscriptions;
```

**Expected Result:**
```
+-------------+------------------------+------------+-----------+
| tenant_name | company_name           | end_date   | is_active |
+-------------+------------------------+------------+-----------+
| restaurant  | ABC Restaurant         | 2026-01-01 | 1         |
| pharmacy    | XYZ Pharmacy           | 2025-02-01 | 1         |
| grocery     | Fresh Grocery Store    | 2025-04-01 | 1         |
| default     | Default Local Testing  | 2099-12-31 | 1         |
+-------------+------------------------+------------+-----------+
```

---

## 🧪 Testing

### Test 1: Valid Subscription (localhost)

1. **Access**: `http://localhost/pos`
2. **Login** with your credentials
3. **Expected**: Dashboard loads normally (default tenant has lifetime subscription)

### Test 2: Expiring Subscription Warning

1. **Update a subscription** to expire soon:
```sql
UPDATE master_subscriptions.client_subscriptions
SET end_date = DATE_ADD(CURDATE(), INTERVAL 5 DAY)
WHERE tenant_name = 'default';
```

2. **Clear cache** (optional):
   - Visit: `http://localhost/pos/subscription/clear_cache` (if logged in as admin)
   - Or wait 1 hour for cache to expire

3. **Refresh dashboard**
4. **Expected**: Yellow warning alert appears

### Test 3: Expired Subscription Block

1. **Set subscription to expired**:
```sql
UPDATE master_subscriptions.client_subscriptions
SET end_date = DATE_SUB(CURDATE(), INTERVAL 5 DAY)
WHERE tenant_name = 'default';
```

2. **Clear cache and reload**
3. **Expected**: Redirected to expiration page with renewal options

### Test 4: Grace Period

1. **Set to within grace period**:
```sql
UPDATE master_subscriptions.client_subscriptions
SET end_date = DATE_SUB(CURDATE(), INTERVAL 1 DAY),
    grace_period_days = 3
WHERE tenant_name = 'default';
```

2. **Expected**: Orange "Grace Period" alert, access still allowed

### Test 5: Restore Normal State

```sql
UPDATE master_subscriptions.client_subscriptions
SET end_date = '2099-12-31'
WHERE tenant_name = 'default';
```

---

## 📖 Usage Examples

### For Developers

#### Check Subscription Programmatically

```php
// In any controller
$this->load->library('subscription_validator');

// Get validation status
$status = $this->subscription_validator->check_validity();

if ($status['is_valid']) {
    echo "Subscription is active";
    echo "Days remaining: " . $status['days_remaining'];
} else {
    echo "Subscription expired: " . $status['message'];
}
```

#### Get Subscription Details

```php
$subscription = $this->subscription_validator->get_subscription_details();
echo "Company: " . $subscription->company_name;
echo "Plan: " . $subscription->subscription_plan;
echo "Expires: " . $subscription->end_date;
```

#### Clear Cache After Manual Update

```php
// After updating subscription in master database
$this->subscription_validator->clear_cache('restaurant');
```

### For Administrators

#### Add New Client Subscription

```sql
INSERT INTO master_subscriptions.client_subscriptions
(tenant_name, company_name, database_name, subscription_plan, start_date, end_date, is_active, contact_email)
VALUES
('newclient', 'New Client Inc', 'webPos_newclient', 'monthly',
 CURDATE(), DATE_ADD(CURDATE(), INTERVAL 1 MONTH), 1, 'admin@newclient.com');
```

#### Renew Existing Subscription

```sql
UPDATE master_subscriptions.client_subscriptions
SET end_date = DATE_ADD(end_date, INTERVAL 1 YEAR)
WHERE tenant_name = 'restaurant';

-- Log the renewal
INSERT INTO master_subscriptions.subscription_history
(subscription_id, action, new_end_date, reason, performed_by)
VALUES
(1, 'renewed', DATE_ADD(CURDATE(), INTERVAL 1 YEAR), 'Annual renewal', 1);
```

#### Suspend Subscription

```sql
UPDATE master_subscriptions.client_subscriptions
SET is_active = 0
WHERE tenant_name = 'problematic_client';
```

#### View Expiring Subscriptions

```sql
SELECT * FROM master_subscriptions.view_active_subscriptions
WHERE days_remaining <= 30 AND days_remaining > 0
ORDER BY days_remaining ASC;
```

---

## 🔧 Troubleshooting

### Issue 1: "Subscription not found" Error

**Cause**: Tenant not in master database

**Solution**:
```sql
-- Add the tenant
INSERT INTO master_subscriptions.client_subscriptions
(tenant_name, company_name, database_name, subscription_plan, start_date, end_date, is_active)
VALUES
('yourtenant', 'Your Company', 'webPos_yourtenant', 'yearly',
 CURDATE(), DATE_ADD(CURDATE(), INTERVAL 1 YEAR), 1);
```

### Issue 2: Alerts Not Showing

**Cause**: Cache not cleared or view not included

**Solution**:
1. Clear cache: Visit `/subscription/clear_cache`
2. Verify `subscription_alert.php` is included in `dashboard.php`
3. Check browser console for JavaScript errors

### Issue 3: Hook Not Running

**Cause**: Hooks not enabled

**Solution**:
```php
// Verify in application/config/config.php
$config['enable_hooks'] = TRUE; // Must be TRUE

// Verify in application/config/hooks.php
// Should have subscription check hook registered
```

### Issue 4: Database Connection Error

**Cause**: Master database credentials incorrect

**Solution**:
- Verify credentials in `application/config/master_database.php`
- Test connection:
```bash
mysql -u root -p master_subscriptions -e "SELECT 1;"
```

### Issue 5: Access Not Blocked When Expired

**Cause**: Block setting disabled

**Solution**:
```php
// In application/config/subscription.php
$config['subscription_block_on_expire'] = TRUE; // Must be TRUE
```

---

## 🔄 Maintenance

### Daily Tasks

1. **Monitor Expiring Subscriptions**:
```sql
SELECT tenant_name, company_name, end_date,
       DATEDIFF(end_date, CURDATE()) as days_left
FROM master_subscriptions.client_subscriptions
WHERE end_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY)
AND is_active = 1;
```

2. **Check Expired Subscriptions**:
```sql
SELECT * FROM master_subscriptions.view_active_subscriptions
WHERE status = 'Expired';
```

### Weekly Tasks

1. **Review Subscription History**:
```sql
SELECT * FROM master_subscriptions.subscription_history
WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
ORDER BY created_at DESC;
```

2. **Clear Old Cache Files** (optional):
```bash
# In application/cache/ directory
find . -name "*.cache" -mtime +7 -delete
```

### Monthly Tasks

1. **Backup Master Database**:
```bash
mysqldump -u root -p master_subscriptions > backup_master_subs_$(date +%Y%m%d).sql
```

2. **Review Performance**:
   - Check cache hit rates
   - Optimize queries if needed
   - Review error logs

### Cache Management

**Manual Cache Clear**:
- Admin URL: `/subscription/clear_cache`
- Or delete: `application/cache/subscription_*.cache`

**Auto-Expiry**: Cache automatically expires after 1 hour

---

## 📊 Monitoring & Reports

### Generate Subscription Report

```sql
SELECT
    cs.tenant_name,
    cs.company_name,
    cs.subscription_plan,
    cs.end_date,
    DATEDIFF(cs.end_date, CURDATE()) as days_remaining,
    CASE
        WHEN cs.is_active = 0 THEN 'Suspended'
        WHEN CURDATE() > cs.end_date THEN 'Expired'
        WHEN DATEDIFF(cs.end_date, CURDATE()) <= 7 THEN 'Expiring Soon'
        ELSE 'Active'
    END as status
FROM master_subscriptions.client_subscriptions cs
ORDER BY cs.end_date ASC;
```

### Revenue Forecast

```sql
SELECT
    subscription_plan,
    COUNT(*) as count,
    SUM(CASE
        WHEN subscription_plan = 'monthly' THEN 50
        WHEN subscription_plan = 'quarterly' THEN 130
        WHEN subscription_plan = 'yearly' THEN 480
        ELSE 0
    END) as projected_revenue
FROM master_subscriptions.client_subscriptions
WHERE is_active = 1 AND end_date > CURDATE()
GROUP BY subscription_plan;
```

---

## 🔐 Security Best Practices

1. **Separate Database User**:
```sql
CREATE USER 'subscription_user'@'localhost' IDENTIFIED BY 'strong_password_here';
GRANT SELECT, INSERT, UPDATE ON master_subscriptions.* TO 'subscription_user'@'localhost';
FLUSH PRIVILEGES;
```

2. **Environment Variables** (Production):
```php
// In master_database.php
$master_db['username'] = getenv('MASTER_DB_USER');
$master_db['password'] = getenv('MASTER_DB_PASS');
```

3. **SSL Connections** (Production):
```php
$master_db['encrypt'] = array(
    'ssl_verify' => true,
    'ssl_ca' => '/path/to/ca-cert.pem'
);
```

4. **Regular Backups**: Daily automated backups of master database

---

## 📞 Support

For issues or questions:
- **Email**: mahfuzcmt@gmail.com
- **Phone**: +8801975585960
- **Documentation**: This file

---

## ✨ Features Summary

- ✅ **1-hour caching** for optimal performance
- ✅ **Automatic validation** on every page load
- ✅ **7-day advance warnings** before expiration
- ✅ **3-day grace period** after expiry
- ✅ **Multi-tenant support** with subdomain detection
- ✅ **Audit trail** of all subscription changes
- ✅ **Flexible alerts** (info/warning/danger levels)
- ✅ **Admin tools** (status viewer, cache control)
- ✅ **Email notifications** (ready for cron setup)
- ✅ **Customizable** via config files

---

## 🎉 Success!

Your subscription management system is now fully operational!

**Next Steps**:
1. Customize support contact information
2. Add your client subscriptions to master database
3. Configure email notifications (optional)
4. Set up automated backups
5. Monitor and maintain regularly

---

**Version**: 1.0.0
**Last Updated**: 2025-01-20
**Created By**: Claude AI Assistant
