<?php
// pages/members.php
requireRole('any'); // Coordinators/Admins can view

// Handle Delete (Admin Only)
if (isset($_GET['delete']) && hasRole('admin')) {
    $id = (int)$_GET['delete'];
    $stmt = $pdo->prepare("DELETE FROM members WHERE id = ?");
    if ($stmt->execute([$id])) {
        $msg = "Member deleted successfully";
    } else {
        $err = $stmt->errorInfo();
        $msg = "Error deleting member: " . ($err[2] ?? "Unknown error");
    }
    // Use JS Redirect to avoid headers sent error
    echo "<script>window.location.href='index.php?page=members&msg=" . urlencode($msg) . "';</script>";
    exit;
}

// Search Logic
$search = isset($_GET['search']) ? clean_input($_GET['search']) : '';
$status_filter = isset($_GET['status']) ? clean_input($_GET['status']) : '';

$sql = "SELECT * FROM members WHERE is_approved = 1";
$params = [];

if (!empty($search)) {
    $sql .= " AND (full_name LIKE ? OR phone LIKE ? OR email LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if (!empty($status_filter)) {
    $sql .= " AND status = ?";
    $params[] = $status_filter;
}

$sql .= " ORDER BY full_name ASC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$members = $stmt->fetchAll();
?>

<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
    <h1>Member Management</h1>
    <?php if(isset($_GET['msg'])): ?>
        <div class="alert alert-info" style="margin: 0; padding: 5px 15px;"><?php echo htmlspecialchars($_GET['msg']); ?></div>
    <?php endif; ?>
    <div style="display: flex; gap: 10px;">
        <?php if (hasRole('roster_manager') || hasRole('admin')): ?>
            <button onclick="generateLink('registration')" class="btn" style="background-color: #e91e63;"><i class="fas fa-link"></i> New Member Link</button>
        <?php endif; ?>
        
        <a href="api/members_export.php" class="btn" style="background-color: var(--success-color);">
            <i class="fas fa-download"></i> Export CSV
        </a>
        <a href="sample_members.csv" download class="btn" style="background-color: #666;">
            <i class="fas fa-file-csv"></i> Sample CSV
        </a>
        <?php if (hasRole('admin') || hasRole('coordinator')): ?>
        <button onclick="document.getElementById('importModal').style.display='block'" class="btn" style="background-color: var(--primary-color);">
            <i class="fas fa-upload"></i> Import CSV
        </button>
        <a href="index.php?page=member_form" class="btn">Add New Member</a>
        <a href="index.php?page=print_form" target="_blank" class="btn" style="background-color: #444;"><i class="fas fa-print"></i> Blank Form</a>
        <?php endif; ?>
    </div>
</div>

<!-- Import Modal -->
<div id="importModal" style="display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.7);">
    <div style="background-color: #222; margin: 10% auto; padding: 30px; border-radius: 8px; width: 90%; max-width: 500px;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h2>Import Members from CSV</h2>
            <button onclick="document.getElementById('importModal').style.display='none'" style="background: none; border: none; color: #fff; font-size: 1.5rem; cursor: pointer;">&times;</button>
        </div>
        
        <form id="importForm" enctype="multipart/form-data">
            <div class="form-group">
                <label>Select CSV File</label>
                <input type="file" name="csv_file" accept=".csv" class="form-control" required>
                <small style="color: #888;">File must match the sample CSV format. <a href="sample_members.csv" download>Download sample</a></small>
            </div>
            <div id="importResult" style="margin: 15px 0; display: none;"></div>
            <button type="submit" class="btn btn-block">Upload and Import</button>
        </form>
    </div>
</div>

<div id="tokenModal" style="display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.7);">
    <div style="background-color: #222; margin: 15% auto; padding: 30px; border-radius: 8px; width: 90%; max-width: 500px; text-align: center;">
        <h3 id="tokenModalTitle">Generated Link</h3>
        <input type="text" id="tokenUrl" class="form-control" style="margin: 15px 0; text-align: center;" readonly>
        <button onclick="copyToken()" class="btn" style="background-color: var(--primary-color);">Copy to Clipboard</button>
        <button onclick="document.getElementById('tokenModal').style.display='none'" class="btn" style="margin-top: 10px; background: transparent; border: 1px solid #555;">Close</button>
    </div>
</div>

<script>
document.getElementById('importForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    const resultDiv = document.getElementById('importResult');
    
    resultDiv.style.display = 'block';
    resultDiv.innerHTML = '<p>Importing...</p>';
    
    try {
        const res = await fetch('api/members_import.php', {
            method: 'POST',
            body: formData
        });
        const result = await res.json();
        
        if (result.success) {
            resultDiv.innerHTML = `<div class="alert alert-success">${result.message}</div>`;
            if (result.errors && result.errors.length > 0) {
                resultDiv.innerHTML += `<div class="alert alert-warning">Warnings:<br>${result.errors.join('<br>')}</div>`;
            }
            setTimeout(() => location.reload(), 2000);
        } else {
            resultDiv.innerHTML = `<div class="alert alert-danger">${result.message}</div>`;
        }
    } catch (error) {
        resultDiv.innerHTML = `<div class="alert alert-danger">Error: ${error.message}</div>`;
    }
});

async function generateLink(type, memberId = null) {
    const formData = new FormData();
    formData.append('type', type);
    if(memberId) formData.append('member_id', memberId);

    try {
        const res = await fetch('api/generate_token.php', { method: 'POST', body: formData });
        const data = await res.json();
        if(data.success) {
            document.getElementById('tokenModalTitle').innerText = type === 'registration' ? 'New Member Registration Link' : 'Member Update Link';
            document.getElementById('tokenUrl').value = data.url;
            document.getElementById('tokenModal').style.display = 'block';
        } else {
            alert('Error: ' + data.message);
        }
    } catch(e) {
        alert('Request failed');
    }
}

function copyToken() {
    const copyText = document.getElementById("tokenUrl");
    copyText.select();
    copyText.setSelectionRange(0, 99999); 
    document.execCommand("copy");
    alert("Copied to clipboard");
}
</script>

<?php
// Fetch Pending Approvals
$pending_stmt = $pdo->query("SELECT * FROM members WHERE is_approved = 0 ORDER BY created_at DESC");
$pending_members = $pending_stmt->fetchAll();
?>

<?php if (!empty($pending_members) && (hasRole('admin') || hasRole('roster_manager'))): ?>
<div class="card" style="margin-bottom: 20px; border-left: 5px solid #ff9800;">
    <h3>Pending Approvals (<?php echo count($pending_members); ?>)</h3>
    <div class="table-responsive">
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Date Registered</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($pending_members as $pm): ?>
                <tr>
                    <td><?php echo htmlspecialchars($pm['full_name']); ?> <small>(<?php echo htmlspecialchars($pm['category']); ?>)</small></td>
                    <td><?php echo date('M j, Y', strtotime($pm['created_at'])); ?></td>
                    <td>
                        <form method="POST" action="api/member_approve.php" style="display:inline;">
                            <input type="hidden" name="id" value="<?php echo $pm['id']; ?>">
                            <button type="submit" name="action" value="approve" class="btn" style="background-color: var(--success-color); padding: 5px 10px; font-size: 0.8rem;">Approve</button>
                            <button type="submit" name="action" value="reject" class="btn" style="background-color: var(--danger-color); padding: 5px 10px; font-size: 0.8rem;" onclick="return confirm('Reject and delete this registration?')">Reject</button>
                        </form>
                         <a href="index.php?page=member_form&id=<?php echo $pm['id']; ?>" class="btn" style="padding: 5px 10px; font-size: 0.8rem; background-color: #666;">View/Edit</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<div class="card" style="margin-bottom: 20px;">
    <form method="GET" style="display: flex; gap: 10px; flex-wrap: wrap;">
        <input type="hidden" name="page" value="members">
        <input type="text" name="search" class="form-control" placeholder="Search Name, Phone, Email" value="<?php echo htmlspecialchars($search); ?>" style="flex: 1;">
        <select name="status" class="form-control" style="width: auto;">
            <option value="">All Statuses</option>
            <option value="Available" <?php if($status_filter == 'Available') echo 'selected'; ?>>Available</option>
            <option value="Not Available" <?php if($status_filter == 'Not Available') echo 'selected'; ?>>Not Available</option>
            <option value="Sick" <?php if($status_filter == 'Sick') echo 'selected'; ?>>Sick</option>
            <option value="Travelled" <?php if($status_filter == 'Travelled' || $status_filter == 'Traveled') echo 'selected'; ?>>Travelled</option>
            <option value="Gospel Errand" <?php if($status_filter == 'Gospel Errand') echo 'selected'; ?>>Gospel Errand</option>
        </select>
        <button type="submit" class="btn">Search</button>
        <?php if($search || $status_filter): ?>
        <a href="index.php?page=members" class="btn" style="background-color: #666;">Clear</a>
        <?php endif; ?>
    </form>
</div>

<div class="table-responsive">
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Phone</th>
                <th>Unit / Role</th>
                <th>Status</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if (count($members) > 0): ?>
                <?php foreach ($members as $m): ?>
                <tr>
                    <td>
                        <div style="font-weight: bold;"><?php echo htmlspecialchars($m['full_name']); ?></div>
                        <div style="font-size: 0.8rem; color: #888;"><?php echo htmlspecialchars($m['email']); ?></div>
                    </td>
                    <td><?php echo htmlspecialchars($m['phone']); ?></td>
                    <td>
                        <?php echo htmlspecialchars($m['unit']); ?> 
                        <?php if($m['unit_role']): ?>
                            <small>(<?php echo htmlspecialchars($m['unit_role']); ?>)</small>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php 
                        $status_color = 'var(--success-color)';
                        if ($m['status'] == 'Not Available') $status_color = 'var(--danger-color)';
                        if ($m['status'] == 'Sick' || $m['status'] == 'Travelled' || $m['status'] == 'Traveled') $status_color = '#ffa000'; // Orange
                        if ($m['status'] == 'Gospel Errand') $status_color = '#9c27b0'; // Purple
                        ?>
                        <span style="color: <?php echo $status_color; ?>; font-weight: bold;">
                            <?php echo htmlspecialchars($m['status']); ?>
                        </span>
                    </td>
                    <td>
                        <?php if (hasRole('roster_manager')): ?>
                            <button onclick="generateLink('update', <?php echo $m['id']; ?>)" class="btn" style="padding: 5px 10px; font-size: 0.8rem; background-color: #00bcd4; color: #fff;" title="Send Update Link"><i class="fas fa-link"></i></button>
                        <?php endif; ?>

                        <?php if (hasRole('roster_manager') || ($_SESSION['user_role'] === 'member' && $m['id'] == $_SESSION['member_id'])): ?>
                        <a href="index.php?page=member_form&id=<?php echo $m['id']; ?>" class="btn" style="padding: 5px 10px; font-size: 0.8rem; background-color: var(--accent-color); color: #000;">Edit</a>
                        <?php endif; ?>
                        
                        <?php if (hasRole('admin')): ?>
                        <a href="index.php?page=members&delete=<?php echo $m['id']; ?>" class="btn" style="padding: 5px 10px; font-size: 0.8rem; background-color: var(--danger-color);" onclick="return confirm('Are you sure you want to delete this member? Attendance records and issues reported by them will be affected.')">Delete</a>
                        <?php endif; ?>
                        
                        <a href="index.php?page=print_form&id=<?php echo $m['id']; ?>" target="_blank" class="btn" style="padding: 5px 10px; font-size: 0.8rem; background-color: #555; color: #fff;" title="Print Form"><i class="fas fa-print"></i></a>
                    </td>
                </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr>
                    <td colspan="5" style="text-align: center;">No members found.</td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>
