<?php
date_default_timezone_set('Asia/Kolkata'); 
include ('../config.php');
include ('whatsapp-api-config.php');
@session_start();
@$user_id1 = $_SESSION['user_id1'];
@$idvfied1 = $_SESSION['idverified1'];
@$namevfied1 = $_SESSION['namevfied1'];
if(!isset($_SESSION['user_id1'])){
	header("Location: index.php");
	exit;
}
$wpq = mysqli_query($conwhatsapp, "SELECT * FROM wp_admin WHERE empid='".@$user_id1."' AND Status='Active'");
$dataWP = mysqli_fetch_array($wpq);

if ($dataWP['empid'] == '') {
	header("Location: dashboard.php");
	exit;
}
$timeout = 60 * 60 * 24 * 365;
$s_name = session_name();
if(isset($_COOKIE[$s_name])) {
  setcookie($s_name, $_COOKIE[$s_name], time() + $timeout, '/');
}

$sel1 = mysqli_query($conn, "SELECT * FROM hr_dump WHERE empid='" . mysqli_real_escape_string($conn, $user_id1) . "'");
$fetch1 = mysqli_fetch_array($sel1);
?>
<?php
$communities = $conwhatsapp->query("SELECT community_id, community_name FROM `communities` ORDER BY community_name ASC");
$members = [];
$selected_community_id = '';
$selected_community_name = '';
$error_msg = '';
$http_code = 0;
$subject_owner = '';

if (isset($_GET['action']) && $_GET['action'] === 'get_members' && !empty($_GET['community_id'])) {
    $community_id = $_GET['community_id'];
    $stmt = $conwhatsapp->prepare("SELECT community_name, subject_owner FROM `communities` WHERE community_id = ? LIMIT 1");
    $stmt->bind_param("s", $community_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $community_name = $row['community_name'];
        $subject_owner = $row['subject_owner'];
    } else {
        echo "<div class='alert alert-danger'>Community not found.</div>";
        exit;
    }
    $stmt->close();
    $encoded_community_id = urlencode($community_id);
    $api_url = rtrim(API_BASE_URL, '/') . "/communities/$encoded_community_id";

    $ch = curl_init($api_url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Authorization: ' . 'Bearer ' . API_TOKEN
        ],
        CURLOPT_SSL_VERIFYPEER => false
    ]);
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $members = [];
    if ($http_code === 200 && $response) {
        $data = json_decode($response, true);
        if (isset($data['participants']) && is_array($data['participants'])) {
            foreach ($data['participants'] as $participant) {
                $raw_id = $participant['id'] ?? '';
                $numeric_phone = preg_replace('/[^\d]/', '', $raw_id);
                $last10 = substr($numeric_phone, -10);
                $formatted_phone = '+91' . $last10;
                $contact_name = 'Unknown';
                $stmt = $conn->prepare("SELECT Employee_Full_Name FROM hr_dump WHERE RIGHT(REPLACE(Official_Mobile_1, ' ', ''), 10) = ? LIMIT 1");
                $stmt->bind_param("s", $last10);
                $stmt->execute();
                $result = $stmt->get_result();
                if ($result && $result->num_rows > 0) {
                    $contact_name = $result->fetch_assoc()['Employee_Full_Name'];
                } elseif (!empty($participant['Employee_Full_Name'])) {
                    $contact_name = $participant['Employee_Full_Name'];
                }
                $stmt->close();

                $members[] = [
                    'Employee_Full_Name' => $contact_name,
                    'Official_Mobile_1' => $formatted_phone,
                    'wa_id' => $numeric_phone . '@s.whatsapp.net'
                ];
            }
        }
    } else {
        echo "<div class='alert alert-danger'>Failed to retrieve community members. HTTP Status Code: $http_code</div>";
        exit;
    }
    if (count($members) > 0) {
        echo '<table id="membersTable" class="table table-striped">';
        echo '<thead class="table-info"><tr><th>Name</th><th>Phone</th></tr></thead><tbody>';
        foreach ($members as $member) {
            $is_owner = ($member['wa_id'] === $subject_owner);
            echo '<tr>';
            echo '<td>' . htmlspecialchars($member['Employee_Full_Name'] ?? 'Unknown') . ($is_owner ? ' <strong>(Owner)</strong>' : '') . '</td>';
            echo '<td>' . htmlspecialchars($member['Official_Mobile_1']) . '</td>';
            echo '</tr>';
        }
        echo '</tbody></table>';
    } else {
        echo '<div class="alert alert-warning">No members found in this community.</div>';
    }
    exit;
}
?>

<!doctype html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, viewport-fit=cover" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>Whatsapp Community Dashboard IC AMS</title>
	<?php	include ('header.php');	?>
	<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
	<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
	<div id="appCapsule">
        <div class="section wallet-card-section pt-1 mb-4">
            <div class="wallet-card">
				<?php	include ('include/wallet-balance.php');	?>
				<div class="row stat-box">
					<div class="col">
						<a href="whatsapp.php"><div class="icon-wrapper"><i class="fas fa-home"></i></div>
							<strong class="pstrong">Whatsapp Home</strong>
						</a>
					</div>
					<div class="col">
						<a href="whatsapp-group-create.php"><div class="icon-wrapper"><i class="fas fa-users-cog"></i></div>
							<strong class="pstrong">Create Group</strong>
						</a>
					</div>
					<div class="col">
						<a href="whatsapp-community-create.php"><div class="icon-wrapper bg-success text-white"><i class="fas fa-users"></i></div>
							<strong class="pstrong">Create Community</strong>
						</a>
					</div>
				</div>
				<div class="row">
                 <div class="col-md-8 mx-auto">
					<div class="card shadow-lg rounded-4">
                        <div class="bg-primary text-white text-center rounded-top py-2">
                            <h4 class="mb-0">View Community Members</h4>
                        </div>
                        <div class="">
                            <?php if (!empty($error_msg)): ?>
                                <div class="alert alert-danger"><?= htmlspecialchars($error_msg) ?></div>
                            <?php endif; ?>

                            <?php if ($communities && $communities->num_rows > 0): ?>
								<div class="table">
									<table id="membersTable" class="table table-striped">
										<thead class="table-info">
											<tr>
												<th>Community Name</th>
											</tr>
										</thead>
										<tbody>
											<?php while ($community = $communities->fetch_assoc()): ?>
												<tr>
													<td>
														<b><?= htmlspecialchars($community['community_name']) ?></b>
														<div class="text-end">
														<button
														type="button" 
															class="btn btn-sm btn-info text-white view-members-btn"
															data-community-id="<?= htmlspecialchars($community['community_id']) ?>"
															data-community-name="<?= htmlspecialchars($community['community_name']) ?>"
															data-bs-toggle="modal"
															data-bs-target="#membersModal">
															View Members
														</button>
														</div>
													</td>
												</tr>
											<?php endwhile; ?>
										</tbody>
									</table>
								</div>
                            <?php else: ?>
                                <div class="alert alert-warning">No communities found.</div>
                            <?php endif; ?>
                        </div>
                        </div>
                    </div>
                    </div>
				</div>
            </div>
        </div>
        <div class="modal fade" id="membersModal" tabindex="-1" aria-labelledby="membersModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg modal-dialog-scrollable">
            <div class="modal-content">
            <div class="modal-header bg-info text-white">
                <h5 class="modal-title" id="membersModalLabel">Community Members</h5>
                <button type="button" class="btn btn-danger" data-bs-dismiss="modal" aria-label="Close">X</button>
            </div>
            <div class="modal-body" id="membersModalBody">
                <div class="text-center text-muted">Loading members...</div>
            </div>
            </div>
        </div>
		<?php	include ('include/copyright.php');	?>
	</div>
    <script>
        $(document).ready(function() {
            $('#membersTable').DataTable({
                "paging": true,
                "searching": true,
                "lengthChange": true,
                "info": true
            });
        });
</script>
<script>
    document.querySelectorAll('.view-members-btn').forEach(button => {
        button.addEventListener('click', () => {
            const communityId = button.getAttribute('data-community-id');
            const communityName = button.getAttribute('data-community-name');
            document.getElementById('membersModalLabel').textContent = `Members of ${communityName}`;
            const modalBody = document.getElementById('membersModalBody');
            
            modalBody.innerHTML = '<div class="text-center text-muted">Loading...</div>';

            fetch('?action=get_members&community_id=' + communityId)
                .then(response => response.text())
                .then(html => {
                    modalBody.innerHTML = html;
                    const membersTable = $('#membersModalBody').find('#membersTable');
                    if (membersTable.length) {
                        membersTable.DataTable({
                            paging: true,
                            searching: true,
                            lengthChange: true,
                            info: true
                        });
                    }
                })
                .catch(error => {
                    modalBody.innerHTML = `<div class="alert alert-danger">Failed to load members.</div>`;
                    console.error(error);
                });
        });
    });
</script>

	<?php	include ('footer.php');	?>