<?php
/**
 * Test Membership System
 * Run this in browser: http://localhost/atasteofafricanmarketplace/test-membership.php
 */

require_once __DIR__ . '/api/lib.php';

header('Content-Type: text/html; charset=UTF-8');

echo '<!DOCTYPE html>
<html>
<head>
    <title>Membership System Test</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 1000px; margin: 40px auto; padding: 20px; }
        .success { color: green; padding: 10px; background: #e6f7e6; border-left: 4px solid green; margin: 10px 0; }
        .error { color: red; padding: 10px; background: #ffe6e6; border-left: 4px solid red; margin: 10px 0; }
        .info { color: blue; padding: 10px; background: #e6f3ff; border-left: 4px solid blue; margin: 10px 0; }
        table { width: 100%; border-collapse: collapse; margin: 20px 0; }
        th, td { padding: 12px; text-align: left; border: 1px solid #ddd; }
        th { background: #0f5240; color: white; }
        .action { background: #d4ad31; color: white; padding: 8px 16px; text-decoration: none; border-radius: 4px; display: inline-block; margin: 5px; }
        h1 { color: #0f5240; }
        h2 { color: #0b3d2e; margin-top: 30px; }
    </style>
</head>
<body>
    <h1>🔧 Membership System Test</h1>
';

try {
    $db = hw_db();
    
    echo '<div class="success">✓ Database connection successful</div>';
    
    // Check if user_memberships table exists
    echo '<h2>1. Database Schema Check</h2>';
    $tables = $db->query("SHOW TABLES LIKE 'user_memberships'")->fetchAll();
    if (count($tables) > 0) {
        echo '<div class="success">✓ user_memberships table exists</div>';
        
        // Get table structure
        $structure = $db->query("DESCRIBE user_memberships")->fetchAll(PDO::FETCH_ASSOC);
        echo '<table><tr><th>Field</th><th>Type</th><th>Null</th><th>Key</th><th>Default</th></tr>';
        foreach ($structure as $col) {
            echo '<tr>';
            echo '<td>' . htmlspecialchars($col['Field']) . '</td>';
            echo '<td>' . htmlspecialchars($col['Type']) . '</td>';
            echo '<td>' . htmlspecialchars($col['Null']) . '</td>';
            echo '<td>' . htmlspecialchars($col['Key']) . '</td>';
            echo '<td>' . htmlspecialchars($col['Default'] ?? 'NULL') . '</td>';
            echo '</tr>';
        }
        echo '</table>';
    } else {
        echo '<div class="error">✗ user_memberships table does not exist</div>';
        echo '<div class="info">Creating table...</div>';
        
        $db->exec("
            CREATE TABLE user_memberships (
                id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT NOT NULL,
                plan_type VARCHAR(50) NOT NULL DEFAULT 'personal',
                status VARCHAR(20) DEFAULT 'active',
                amount DECIMAL(10,2) NOT NULL,
                paypal_order_id VARCHAR(100),
                paypal_payment_id VARCHAR(100),
                starts_at DATETIME NOT NULL,
                expires_at DATETIME NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
                UNIQUE KEY unique_user_membership (user_id)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
        ");
        
        echo '<div class="success">✓ Table created successfully</div>';
    }
    
    // Check existing memberships
    echo '<h2>2. Current Memberships</h2>';
    $memberships = $db->query("
        SELECT um.*, u.email, u.first_name, u.last_name,
               CASE 
                   WHEN um.expires_at > NOW() THEN 'ACTIVE'
                   ELSE 'EXPIRED'
               END as actual_status
        FROM user_memberships um
        LEFT JOIN users u ON um.user_id = u.id
        ORDER BY um.created_at DESC
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    if (count($memberships) > 0) {
        echo '<table>';
        echo '<tr><th>User</th><th>Email</th><th>Plan Type</th><th>Amount</th><th>Status</th><th>Expires</th><th>Actual Status</th></tr>';
        foreach ($memberships as $m) {
            $statusClass = $m['actual_status'] === 'ACTIVE' ? 'success' : 'error';
            echo '<tr>';
            echo '<td>' . htmlspecialchars($m['first_name'] . ' ' . $m['last_name']) . '</td>';
            echo '<td>' . htmlspecialchars($m['email']) . '</td>';
            echo '<td><strong>' . htmlspecialchars(ucfirst($m['plan_type'])) . '</strong></td>';
            echo '<td>$' . number_format($m['amount'], 2) . '</td>';
            echo '<td>' . htmlspecialchars($m['status']) . '</td>';
            echo '<td>' . htmlspecialchars($m['expires_at']) . '</td>';
            echo '<td class="' . $statusClass . '">' . $m['actual_status'] . '</td>';
            echo '</tr>';
        }
        echo '</table>';
    } else {
        echo '<div class="info">No memberships found</div>';
    }
    
    // Get test users
    echo '<h2>3. Test Users (Clients)</h2>';
    $users = $db->query("
        SELECT u.*, 
               um.plan_type, um.status as membership_status, um.expires_at,
               CASE 
                   WHEN um.id IS NOT NULL AND um.expires_at > NOW() AND um.status = 'active' THEN 'HAS ACCESS'
                   ELSE 'NEEDS PLAN'
               END as dashboard_access
        FROM users u
        LEFT JOIN user_memberships um ON u.id = um.user_id
        WHERE u.id IN (SELECT user_id FROM users WHERE email LIKE '%test%' OR email LIKE '%client%')
        OR u.id IN (1,2,3,4,5,6)
        LIMIT 10
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    if (count($users) > 0) {
        echo '<table>';
        echo '<tr><th>ID</th><th>Name</th><th>Email</th><th>Plan</th><th>Expires</th><th>Dashboard Access</th><th>Action</th></tr>';
        foreach ($users as $u) {
            $accessClass = $u['dashboard_access'] === 'HAS ACCESS' ? 'success' : 'error';
            echo '<tr>';
            echo '<td>' . $u['id'] . '</td>';
            echo '<td>' . htmlspecialchars($u['first_name'] . ' ' . $u['last_name']) . '</td>';
            echo '<td>' . htmlspecialchars($u['email']) . '</td>';
            echo '<td>' . ($u['plan_type'] ? htmlspecialchars(ucfirst($u['plan_type'])) : 'None') . '</td>';
            echo '<td>' . ($u['expires_at'] ?? 'N/A') . '</td>';
            echo '<td class="' . $accessClass . '">' . $u['dashboard_access'] . '</td>';
            echo '<td>';
            if ($u['dashboard_access'] === 'NEEDS PLAN') {
                echo '<a href="?activate=' . $u['id'] . '&plan=personal" class="action">Activate Personal</a>';
                echo '<a href="?activate=' . $u['id'] . '&plan=family" class="action" style="background: #0f5240;">Activate Family</a>';
            }
            echo '</td>';
            echo '</tr>';
        }
        echo '</table>';
    } else {
        echo '<div class="info">No test users found</div>';
    }
    
    // Handle activation
    if (isset($_GET['activate']) && isset($_GET['plan'])) {
        $userId = (int)$_GET['activate'];
        $planType = $_GET['plan'] === 'family' ? 'family' : 'personal';
        $amount = $planType === 'family' ? 99.00 : 49.00;
        
        try {
            $stmt = $db->prepare("
                INSERT INTO user_memberships (user_id, plan_type, status, amount, paypal_order_id, paypal_payment_id, starts_at, expires_at)
                VALUES (?, ?, 'active', ?, ?, ?, NOW(), DATE_ADD(NOW(), INTERVAL 1 MONTH))
                ON DUPLICATE KEY UPDATE
                    plan_type = VALUES(plan_type),
                    status = 'active',
                    amount = VALUES(amount),
                    expires_at = DATE_ADD(NOW(), INTERVAL 1 MONTH)
            ");
            $stmt->execute([
                $userId,
                $planType,
                $amount,
                'TEST_ORDER_' . time(),
                'TEST_PAY_' . uniqid()
            ]);
            
            echo '<div class="success">✓ Activated ' . ucfirst($planType) . ' plan for user ID ' . $userId . '</div>';
            echo '<script>setTimeout(function(){ location.href = "test-membership.php"; }, 2000);</script>';
        } catch (Exception $e) {
            echo '<div class="error">✗ Failed to activate: ' . htmlspecialchars($e->getMessage()) . '</div>';
        }
    }
    
    // File checks
    echo '<h2>4. File Checks</h2>';
    $files = [
        'dashboard/user/choose-plan.php' => 'Plan Selection Page',
        'dashboard/user/index.php' => 'Client Dashboard',
        'dashboard/user/membership.php' => 'Membership Management',
        'api/membership/activate.php' => 'Activation API',
        'api/membership/status.php' => 'Status API',
    ];
    
    foreach ($files as $file => $name) {
        $fullPath = __DIR__ . '/' . $file;
        if (file_exists($fullPath)) {
            echo '<div class="success">✓ ' . htmlspecialchars($name) . ' exists</div>';
        } else {
            echo '<div class="error">✗ ' . htmlspecialchars($name) . ' missing</div>';
        }
    }
    
    echo '<h2>5. Quick Links</h2>';
    echo '<a href="/atasteofafricanmarketplace/dashboard/user/choose-plan.php" class="action">View Plan Selection</a>';
    echo '<a href="/atasteofafricanmarketplace/dashboard/user/index.php" class="action">Client Dashboard</a>';
    echo '<a href="/atasteofafricanmarketplace/login-choice.php" class="action" style="background: #0f5240;">Login Page</a>';
    
} catch (Exception $e) {
    echo '<div class="error">✗ Error: ' . htmlspecialchars($e->getMessage()) . '</div>';
}

echo '</body></html>';
?>
