<?php
require_once 'vendor/autoload.php';
require_once 'config.php';

/**
 * Admin interface to manage consent requests
 */

// Check if admin is logged in (add your own authentication)
$adminParam = $_GET['admin'] ?? '';
$debugMode = true; // Set to false after testing

if ($debugMode) {
    echo "<h3>Debug Info:</h3>";
    echo "Admin parameter received: '" . htmlspecialchars($adminParam) . "'<br>";
    echo "Expected: 'Homiez@420'<br>";
    echo "Match: " . ($adminParam === 'Homiez@420' ? 'YES' : 'NO') . "<br><hr>";
}

if (!isset($_GET['admin']) || $_GET['admin'] !== 'Homiez@420') {
    if ($debugMode) {
        echo "<h1>Access Denied (Debug Mode)</h1>";
        echo "<p>Try: ?admin=Homiez@420</p>";
        echo "<p>Or try: ?admin=Homiez%40420</p>";
    } else {
        die("<h1>Access Denied</h1><p>Admin access required</p>");
    }
}

try {
    // Connect to database
    $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";
    $options = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ];
    $pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
    
    // Handle approval/denial actions
    if (isset($_POST['action']) && isset($_POST['phone'])) {
        $phone = $_POST['phone'];
        $action = $_POST['action'];
        
        if ($action === 'approve') {
            $status = 'approved';
        } elseif ($action === 'deny') {
            $status = 'denied';
        } else {
            die("Invalid action");
        }
        
        $sql = "UPDATE consent_requests 
                SET consent_status = ?, response_date = CURRENT_TIMESTAMP
                WHERE phone_number = ? AND consent_status = 'pending'";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$status, $phone]);
        
        echo "<div class='alert alert-success'>Consent for $phone updated to $status</div>";
    }
    
    // Get all pending requests
    $sql = "SELECT phone_number, consent_token, request_date, ip_address, user_agent
            FROM consent_requests 
            WHERE consent_status = 'pending'
            ORDER BY request_date DESC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $pending = $stmt->fetchAll();
    
    // Get statistics
    $statsSql = "SELECT consent_status, COUNT(*) as count 
                 FROM consent_requests 
                 GROUP BY consent_status";
    $statsStmt = $pdo->prepare($statsSql);
    $statsStmt->execute();
    $stats = $statsStmt->fetchAll();
    
} catch (Exception $e) {
    die("Error: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Consent Management Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-4">
        <h1>Consent Management Admin</h1>
        
        <!-- Statistics -->
        <div class="row mb-4">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">Statistics</div>
                    <div class="card-body">
                        <?php foreach ($stats as $stat): ?>
                            <span class="badge bg-<?php echo $stat['consent_status'] === 'approved' ? 'success' : ($stat['consent_status'] === 'denied' ? 'danger' : 'warning'); ?> me-2">
                                <?php echo ucfirst($stat['consent_status']); ?>: <?php echo $stat['count']; ?>
                            </span>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Pending Requests -->
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">Pending Consent Requests</div>
                    <div class="card-body">
                        <?php if (empty($pending)): ?>
                            <p class="text-muted">No pending consent requests</p>
                        <?php else: ?>
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Phone Number</th>
                                        <th>Request Date</th>
                                        <th>IP Address</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($pending as $request): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($request['phone_number']); ?></td>
                                            <td><?php echo $request['request_date']; ?></td>
                                            <td><?php echo htmlspecialchars($request['ip_address']); ?></td>
                                            <td>
                                                <form method="POST" class="d-inline">
                                                    <input type="hidden" name="phone" value="<?php echo htmlspecialchars($request['phone_number']); ?>">
                                                    <button type="submit" name="action" value="approve" class="btn btn-success btn-sm">Approve</button>
                                                    <button type="submit" name="action" value="deny" class="btn btn-danger btn-sm">Deny</button>
                                                </form>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>