# Subscription Blocking System - Complete Setup Guide

**Feature**: Full-page modal overlay blocking after 3-day grace period
**Status**: ✅ Fully Implemented
**Last Updated**: 2025-11-20

---

## ✅ WHAT WAS IMPLEMENTED

### 1. Full-Page Modal Overlay
- **File Created**: `application/views/subscription_expired_modal.php`
- **Behavior**:
  - Displays on top of ANY page user tries to access
  - Cannot be dismissed or closed
  - Blocks all page interaction
  - Shows subscription details and contact information
  - Prevents keyboard shortcuts (F5, Ctrl+R, Escape)

### 2. Hook Modification
- **File Modified**: `application/hooks/Subscription_check.php`
- **Changes**:
  - Injects modal overlay instead of redirecting
  - Uses output buffering to insert modal into page
  - Logs blocked attempts with details
  - Continues page render with modal on top

### 3. Hook Enabled
- **File Modified**: `application/config/hooks.php`
- **Status**: Uncommented (ACTIVE)
- **Triggers**: After every controller construction

### 4. Configuration Updates
- **File Modified**: `application/config/subscription.php`
- **Changes**:
  - Added company name: "Bitsoft IT Solution"
  - Added WhatsApp number: +8801975585960
  - Removed 'subscription' from bypass controllers
  - Only login/logout pages accessible when expired

### 5. Complete Blocking
- **Bypass Controllers**: Only `login` and `logout`
- **Blocked**: Everything else including admin pages, subscription pages
- **Result**: Forces contact with support for renewal

---

## 🗄️ DATABASE SETUP

### Required: Master Subscriptions Database

**Database**: `master_subscriptions`
**Import File**: `database/master_subscription_db.sql`

**Key Table**: `client_subscriptions`

### SQL Queries for Setup

#### 1. Set All Tenants to 3-Day Grace Period

```sql
USE master_subscriptions;

-- Update all existing subscriptions to 3-day grace period
UPDATE client_subscriptions
SET grace_period_days = 3
WHERE grace_period_days != 3;

-- Verify update
SELECT tenant_name, company_name, subscription_plan, end_date, grace_period_days
FROM client_subscriptions;
```

#### 2. Check Current Subscription Status

```sql
USE master_subscriptions;

-- View all subscriptions with status
SELECT
    tenant_name,
    company_name,
    subscription_plan,
    end_date,
    grace_period_days,
    DATE_ADD(end_date, INTERVAL grace_period_days DAY) AS grace_end_date,
    DATEDIFF(NOW(), end_date) AS days_past_expiry,
    CASE
        WHEN is_active = 0 THEN 'Suspended'
        WHEN NOW() > DATE_ADD(end_date, INTERVAL grace_period_days DAY) THEN 'BLOCKED (Expired + Grace)'
        WHEN NOW() > end_date THEN 'Grace Period'
        WHEN DATEDIFF(end_date, NOW()) <= 7 THEN 'Expiring Soon'
        ELSE 'Active'
    END AS status
FROM client_subscriptions
ORDER BY end_date ASC;
```

#### 3. Test Subscription Blocking

```sql
USE master_subscriptions;

-- TESTING: Force expire a tenant (for testing modal overlay)
-- Replace 'restaurant' with actual tenant name
UPDATE client_subscriptions
SET end_date = DATE_SUB(NOW(), INTERVAL 5 DAY)  -- 5 days ago (past grace period)
WHERE tenant_name = 'restaurant';

-- TESTING: Set tenant to grace period (shows warning but allows access)
UPDATE client_subscriptions
SET end_date = DATE_SUB(NOW(), INTERVAL 1 DAY)  -- 1 day ago (within grace)
WHERE tenant_name = 'restaurant';

-- TESTING: Reset to active subscription
UPDATE client_subscriptions
SET end_date = DATE_ADD(NOW(), INTERVAL 30 DAY)  -- 30 days from now
WHERE tenant_name = 'restaurant';
```

#### 4. Add New Tenant Subscription

```sql
USE master_subscriptions;

INSERT INTO client_subscriptions (
    tenant_name,
    company_name,
    database_name,
    subscription_plan,
    start_date,
    end_date,
    is_active,
    grace_period_days,
    max_users,
    features_enabled,
    contact_email,
    contact_phone,
    created_at,
    updated_at
) VALUES (
    'newclient',                          -- Subdomain
    'New Client Company Name',            -- Display name
    'webPos_newclient',                   -- Database name
    'monthly',                            -- trial|monthly|quarterly|yearly
    NOW(),                                -- Start date
    DATE_ADD(NOW(), INTERVAL 30 DAY),    -- End date (30 days from now)
    1,                                    -- Active
    3,                                    -- 3-day grace period
    5,                                    -- Max 5 users
    '["sales", "inventory", "reports"]',  -- Features JSON
    'client@email.com',                   -- Contact email
    '+880XXXXXXXXXX',                     -- Contact phone
    NOW(),                                -- Created
    NOW()                                 -- Updated
);
```

---

## 🧪 TESTING PROCEDURE

### Test Scenario 1: Active Subscription
**Expected**: Normal operation, no blocking

**Steps**:
1. Set `end_date` to future: `DATE_ADD(NOW(), INTERVAL 30 DAY)`
2. Access http://localhost/pos/
3. Login with valid credentials
4. Navigate to any page

**Result**: ✅ Full access, no warnings

---

### Test Scenario 2: Within Grace Period (1-3 days past expiry)
**Expected**: Yellow warning banner, access allowed

**SQL**:
```sql
UPDATE client_subscriptions
SET end_date = DATE_SUB(NOW(), INTERVAL 2 DAY)  -- 2 days ago
WHERE tenant_name = 'default';  -- Use 'default' for localhost testing
```

**Steps**:
1. Clear cache: http://localhost/pos/subscription/clear_cache
2. Access http://localhost/pos/
3. Login with valid credentials

**Result**: ⚠️ Warning banner shows "Grace period ends in 1 day" but access allowed

---

### Test Scenario 3: After Grace Period (4+ days past expiry)
**Expected**: Full-page modal overlay, complete block

**SQL**:
```sql
UPDATE client_subscriptions
SET end_date = DATE_SUB(NOW(), INTERVAL 5 DAY)  -- 5 days ago (past 3-day grace)
WHERE tenant_name = 'default';  -- Use 'default' for localhost testing
```

**Steps**:
1. Clear cache: http://localhost/pos/subscription/clear_cache
2. Access http://localhost/pos/
3. Login with valid credentials
4. Try to navigate to any page

**Result**: 🚫 **BLOCKED**
- Full-page modal overlay appears
- Shows: "Subscription Expired"
- Displays expiry date and days overdue
- Shows contact information
- Cannot dismiss modal
- Cannot interact with page underneath
- Cannot access any functionality

**Verify Blocking**:
- Try clicking anywhere on page → Blocked
- Try pressing Escape → Blocked
- Try pressing F5 → Blocked
- Try Ctrl+R → Blocked
- Try accessing /users → Blocked
- Try accessing /sales → Blocked
- Try accessing /subscription/status → Blocked

**Can Still Do**:
- ✅ Logout (to allow user to leave)
- ✅ Copy contact information from modal

---

### Test Scenario 4: AJAX Requests When Blocked
**Expected**: AJAX requests should also be blocked

**Steps**:
1. With subscription blocked (past grace period)
2. Open browser console (F12)
3. Try to make AJAX request

**Result**: Request should be intercepted and blocked

---

## 📋 CONFIGURATION REFERENCE

**File**: `application/config/subscription.php`

### Key Settings:

```php
// Support Contact Information (displayed in modal)
$config['subscription_support_email'] = 'mahfuzcmt@gmail.com';
$config['subscription_support_phone'] = '+8801975585960';
$config['subscription_support_company'] = 'Bitsoft IT Solution';
$config['subscription_support_whatsapp'] = '+8801975585960';

// Blocking Behavior
$config['subscription_block_on_expire'] = TRUE;        // Hard block enabled
$config['subscription_allow_grace_period'] = TRUE;     // Allow access during grace

// Grace Period (set in database, defaults to 3 days)
// Each tenant can have different grace period in client_subscriptions table

// Pages That Bypass Blocking
$config['subscription_bypass_controllers'] = array('login', 'logout');

// Alert Thresholds
$config['subscription_alert_warning'] = 7;   // Show warning 7 days before expiry
$config['subscription_alert_critical'] = 3;  // Critical alert 3 days before

// Cache Settings
$config['subscription_cache_enabled'] = TRUE;
$config['subscription_cache_duration'] = 3600;  // 1 hour
```

---

## 🔍 TROUBLESHOOTING

### Issue 1: Modal Not Appearing

**Check**:
1. Hook enabled: `application/config/hooks.php` (lines 24-30)
2. Subscription past grace: Check `end_date` + `grace_period_days`
3. Clear cache: http://localhost/pos/subscription/clear_cache
4. Check logs: `application/logs/log-YYYY-MM-DD.php`

**Debug**:
```sql
-- Check subscription status
USE master_subscriptions;
SELECT
    tenant_name,
    end_date,
    grace_period_days,
    DATE_ADD(end_date, INTERVAL grace_period_days DAY) AS grace_end,
    DATEDIFF(NOW(), DATE_ADD(end_date, INTERVAL grace_period_days DAY)) AS days_past_grace
FROM client_subscriptions
WHERE tenant_name = 'default';
```

---

### Issue 2: Still Can Access Pages When Blocked

**Possible Causes**:
- Controller added to bypass list
- Cache not cleared
- Session has old subscription data

**Fix**:
```sql
-- Force expire
UPDATE client_subscriptions
SET end_date = DATE_SUB(NOW(), INTERVAL 10 DAY)
WHERE tenant_name = 'default';
```

Then:
1. Clear cache: http://localhost/pos/subscription/clear_cache
2. Logout and login again
3. Clear browser cache (Ctrl+Shift+Delete)

---

### Issue 3: Master Database Connection Error

**Error**: "Unable to connect to master_subscriptions database"

**Fix**:
1. Verify database exists:
   ```sql
   SHOW DATABASES LIKE 'master_subscriptions';
   ```

2. If not exists, import:
   ```bash
   mysql -u root -p < database/master_subscription_db.sql
   ```

3. Check credentials in `application/config/master_database.php`

---

### Issue 4: Modal Shows But Contact Info Missing

**Check**: `application/config/subscription.php` lines 39-48

**Verify**:
```php
$config['subscription_support_email'] = 'mahfuzcmt@gmail.com';
$config['subscription_support_phone'] = '+8801975585960';
$config['subscription_support_company'] = 'Bitsoft IT Solution';
```

---

## 🚀 DEPLOYMENT TO cPANEL

### Checklist:

- [ ] Upload master_subscription_db.sql to cPanel
- [ ] Create `master_subscriptions` database
- [ ] Import SQL file
- [ ] Update `application/config/master_database.php` with cPanel credentials
- [ ] Update `application/config/subscription.php` with production contact info
- [ ] Set all tenant grace periods to 3 days
- [ ] Test with one expired tenant first
- [ ] Clear cache after deployment
- [ ] Monitor `application/logs/` for errors

---

## 📞 CONTACT INFORMATION (Displayed in Modal)

**Company**: Bitsoft IT Solution
**Email**: mahfuzcmt@gmail.com
**Phone**: +8801975585960
**WhatsApp**: +8801975585960

**To Update**: Edit `application/config/subscription.php` lines 39-48

---

## 💡 BEST PRACTICES

### 1. Grace Period Management
- Use 3 days for most clients
- Extend to 7 days for premium clients
- Set to 0 days for strict blocking

### 2. Monitoring
- Check `application/logs/` daily for blocked access attempts
- Review `subscription_history` table weekly
- Monitor `subscription_alerts` for notification tracking

### 3. Renewal Process
- When client pays, update `end_date` in database
- Set `is_active = 1`
- Clear cache for that tenant
- Send confirmation email

### 4. Testing Before Client Launch
- Always test with expired date first
- Verify modal displays correctly
- Check contact information is accurate
- Test on mobile devices too

---

**Implementation Status**: ✅ Complete and Ready for Production
**Date**: 2025-11-20
**Developer**: Claude AI Assistant

