<?php
/**
 * Admin Folder Security Configuration
 * 
 * This file documents the security measures implemented for the admin folder.
 * All access to admin pages is protected by authentication checks.
 */

/**
 * SECURITY MEASURES IMPLEMENTED:
 * 
 * 1. PHP-Level Authentication
 *    - Every PHP file in /admin/ includes Auth class
 *    - $auth->requireLogin() prevents unauthenticated access
 *    - Automatic redirect to login page if not authenticated
 *    - Optional role checking with $auth->requireRole()
 *
 * 2. Session Management
 *    - Session-based authentication
 *    - User info stored in $_SESSION after successful login
 *    - Session destroyed on logout
 *    - Automatic session validation
 *
 * 3. Apache .htaccess Protection
 *    - Prevents directory listing
 *    - Blocks access to sensitive files (.env, .git, .htaccess)
 *    - Sets security headers (XSS protection, clickjacking prevention)
 *    - Disables caching for admin pages
 *    - MIME type protection
 *
 * 4. Role-Based Access Control (RBAC)
 *    - Admin: Full system access
 *    - Staff: Operational access
 *    - Viewer: Read-only access
 *    - Enforced with $auth->requireRole('role_name')
 */

/**
 * PROTECTED PAGES:
 */
$protected_pages = [
    'dashboard.php'          => 'Main admin dashboard - Any authenticated user',
    'index.php'              => 'Admin index - Any authenticated user',
    'customers.php'          => 'Customer management - Any authenticated user',
    'loan_requests.php'      => 'Loan requests - Any authenticated user',
    'mpesa_transactions.php' => 'M-Pesa transactions - Any authenticated user',
    'stk_requests.php'       => 'STK push requests - Any authenticated user',
    'whitelist.php'          => 'Whitelist management - Any authenticated user',
    'settings.php'           => 'System settings - Any authenticated user',
    'update_paybills.php'    => 'Update paybills - Any authenticated user',
    'export_phones.php'      => 'Export contacts - Any authenticated user',
    'delete_stk.php'         => 'Delete STK records - Any authenticated user',
    'users.php'              => 'User management - ADMIN ONLY',
];

/**
 * PUBLIC PAGES (Outside admin folder):
 */
$public_pages = [
    '/login.php'    => 'Authentication page - No login required',
    '/setup.php'    => 'Initial setup - No login required',
    '/index.php'    => 'USSD API endpoint - No authentication needed',
    '/callback.php' => 'Callback handler - No authentication needed',
];

/**
 * HOW IT WORKS:
 */

/**
 * LOGIN FLOW:
 * User visits /login.php
 *     ↓
 * Enters credentials
 *     ↓
 * Auth::login() validates credentials
 *     ↓
 * If valid: Create session → Redirect to dashboard
 * If invalid: Show error message
 */

/**
 * ACCESS PROTECTED PAGE FLOW:
 * User visits /dashboard.php
 *     ↓
 * Page includes Auth class
 *     ↓
 * Calls $auth->requireLogin()
 *     ↓
 * If logged in: Continue loading page
 * If not logged in: Redirect to /login.php
 */

/**
 * LOGOUT FLOW:
 * User clicks Logout in sidebar
 *     ↓
 * Visits /ussd/logout.php
 *     ↓
 * Auth::logout() is called
 *     ↓
 * Session destroyed
 *     ↓
 * Redirect to /login.php
 */

/**
 * CODE EXAMPLES:
 */

// Example 1: Basic authentication check
/*
<?php
require_once '../src/Auth.php';
$auth = new Auth();
$auth->requireLogin();  // Redirects to login if not authenticated
?>
*/

// Example 2: Admin-only page
/*
<?php
require_once '../src/Auth.php';
$auth = new Auth();
$auth->requireLogin();           // Must be logged in
$auth->requireRole('admin');     // Must be admin
?>
*/

// Example 3: Get current user info
/*
<?php
require_once '../src/Auth.php';
$auth = new Auth();
$auth->requireLogin();

$user = $auth->getCurrentUser();
echo "Welcome " . $user['full_name'];
echo "Role: " . $user['role'];
?>
*/

/**
 * SECURITY CHECKLIST:
 */
$security_checklist = [
    '✅ All admin pages require authentication' => 'Every .php file in /admin/ has $auth->requireLogin()',
    '✅ Session management' => 'Proper session creation and destruction',
    '✅ Password hashing' => 'Bcrypt hashing with PASSWORD_BCRYPT',
    '✅ SQL injection protection' => 'Prepared statements with parameter binding',
    '✅ XSS protection' => 'htmlspecialchars() for output escaping',
    '✅ Role-based access control' => 'User roles (Admin, Staff, Viewer)',
    '✅ Directory listing disabled' => '.htaccess prevents browsing',
    '✅ Sensitive files blocked' => '.htaccess blocks .env, .git, .htaccess',
    '✅ Security headers' => 'X-Frame-Options, X-Content-Type-Options, etc.',
    '✅ Cache disabled' => 'No-cache headers for admin pages',
];

/**
 * TESTING SECURITY:
 */

// Test 1: Try accessing /admin/dashboard.php without login
// Expected: Redirect to /admin/login.php

// Test 2: Try accessing /admin/users.php as staff member
// Expected: Redirect to /admin/dashboard.php (requires admin role)

// Test 3: Try accessing /admin/delete_stk.php in incognito window
// Expected: Redirect to /admin/login.php (no session)

// Test 4: Create new session and verify page access
// Expected: Page loads with user data displayed

/**
 * ADDING NEW ADMIN PAGES:
 */
/*
1. Create new file in /admin/ folder
2. Add at the top:
   <?php
   require_once '../src/Database.php';
   require_once '../src/Auth.php';
   
   $auth = new Auth();
   $auth->requireLogin();
   // Optionally: $auth->requireRole('admin');
   ?>

3. Rest of your page code below
4. If admin-only, uncomment requireRole line
5. Include sidebar for navigation: <?php include 'sidebar.php'; ?>
6. Add menu item to sidebar.php
*/

/**
 * TROUBLESHOOTING:
 */

// Issue: Keep getting redirected to login
// Solution: Check if session is enabled in php.ini, verify database connection

// Issue: Users can't access their role-specific pages
// Solution: Check role assignment in users table, verify $auth->requireRole() is set

// Issue: Session expires too quickly
// Solution: Adjust session.gc_maxlifetime in php.ini (default: 1440 seconds / 24 minutes)

// Issue: .htaccess not working
// Solution: Ensure AllowOverride is set to All in Apache configuration

/**
 * FILES SUMMARY:
 */
// /admin/login.php - Authentication (no requireLogin check - that's the entry point)
// /admin/dashboard.php - Dashboard (requireLogin)
// /admin/customers.php - Customers (requireLogin)
// /admin/users.php - Users (requireLogin + requireRole('admin'))
// /admin/[other pages] - All require authentication

/**
 * END OF SECURITY DOCUMENTATION
 */
