<?php
date_default_timezone_set('Asia/Kolkata'); 
//echo $date = date("Y-m-d", time());
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");
}
$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='".@$user_id1."'");
$fetch1=mysqli_fetch_array($sel1);
?>

<!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>Create Whatsapp Community IC AMS</title>
 
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
	<?php	include ('header.php');	?>
	<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-sm-6 p-2">
						<div class="row stat-box">
		<?php
			  if (isset($_SESSION['success_msg'])) {
				  echo "<div class='alert alert-success'>" . $_SESSION['success_msg'] . "</div>";
				  unset($_SESSION['success_msg']);
			  }
			  if (isset($_SESSION['error_msg'])) {
				  echo "<div class='alert alert-danger'>" . $_SESSION['error_msg'] . "</div>";
				  unset($_SESSION['error_msg']);
			  }
		?>
							
							<h6 class="text-center">Create Whatsapp Community</h6>
							 <form action="" method="POST">
								<div class="mb-3">
									<input type="text" class="form-control" id="community_name" name="community_name" placeholder="Enter community name..." required>
								</div>
								<div class="mb-3">
									<textarea class="form-control" id="community_description" name="community_description" rows="3" placeholder="Enter community description..."></textarea>
								</div>
								<div class="d-grid">
									<button type="submit" class="btn btn-primary mb-2">Create Community</button>
								</div>
							</form>
            <?php

            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                if (empty($_POST['community_name'])) {
                    die("❌ Error: Community name is required.");
                }

                $community_name = trim($_POST['community_name']);
                $description = trim($_POST['community_description'] ?? '');

                $payload = [
                    'subject' => $community_name,
                    'description' => $description
                ];

                $create_url = rtrim(API_BASE_URL, '/') . '/communities';

                $ch = curl_init($create_url);
                curl_setopt_array($ch, [
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_POST => true,
                    CURLOPT_POSTFIELDS => json_encode($payload),
                    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);

                if ($response === false || ($http_code !== 200 && $http_code !== 201)) {
                    die("❌ Error: Community creation failed. API response:<br><pre>" . htmlspecialchars($response ?? 'No response') . "</pre>");
                }

                $data = json_decode($response, true);

                if (!isset($data['id'])) {
                    die("❌ Error: API response missing community ID.");
                }

                $community_id = $data['id'];

                // Wait before fetching invite code (optional)
                sleep(2);

                $invite_url = null;
                $max_retries = 5;
                $retry_delay = 2;
                $retried = 0;

                do {
                    $community_details_url = rtrim(API_BASE_URL, '/') . '/communities/' . urlencode($community_id);

                    $ch = curl_init($community_details_url);
                    curl_setopt_array($ch, [
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_HTTPHEADER => [
                            'Authorization: Bearer ' . API_TOKEN,
                            'Accept: application/json'
                        ],
                        CURLOPT_SSL_VERIFYPEER => false,
                    ]);

                    $details_response = curl_exec($ch);
                    $details_http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                    curl_close($ch);

                    if ($details_response !== false && $details_http_code === 200) {
                        $details_data = json_decode($details_response, true);
                        if (isset($details_data['invite_code']) && !empty($details_data['invite_code'])) {
                            $invite_code = $details_data['invite_code'];
                            $invite_url = "https://chat.whatsapp.com/" . $invite_code;
                            break;
                        }
                    }
                    $retried++;
                    if ($retried < $max_retries) {
                        sleep($retry_delay);
                    }
                } while ($retried < $max_retries);

                if ($invite_url === null) {
                    die("❌ Error: Could not retrieve invite URL after multiple attempts. Community not created.");
                }

                $empid = $fetch1['empid'] ?? '';
                $Employee_Full_Name = $fetch1['Employee_Full_Name'] ?? '';
                $Official_Mobile_1 = $fetch1['Official_Mobile_1'] ?? '';

                $stmt = $conwhatsapp->prepare("INSERT INTO communities (community_id, community_name, description, subject_owner, invite_url, empid, Employee_Full_Name, Official_Mobile_1, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");

                if (!$stmt) {
                    die("❌ DB Error: " . htmlspecialchars($conwhatsapp->error));
                }

                $subject_owner = $data['subjectOwner'] ?? '';

                $stmt->bind_param("ssssssss", $community_id, $community_name, $description, $subject_owner, $invite_url, $empid, $Employee_Full_Name, $Official_Mobile_1);

                if (!$stmt->execute()) {
                    $stmt->close();
                    die("❌ DB Error: " . htmlspecialchars($stmt->error));
                }

                $stmt->close();
			
				$_SESSION['success_msg'] = "<h6>✅ Community created successfully!</h6><h6>$community_name</h6>";
				echo "<script>window.location.href='whatsapp-community-create.php?created=1';</script>";
				exit;
				
            }
            ?>
						</div> 
					</div>
					<div class="col-sm-6 p-2">
						<div class="row stat-box">
							<h6 class="text-center">Whatsapp Community List</h6>
							<div class="text-start">
									<?php
									$res = $conwhatsapp->query("SELECT id, community_id, community_name, invite_url FROM communities ORDER BY id DESC");
									if ($res && $res->num_rows > 0) {
										echo "<ul class='list-group list-group-flush'>";
										while ($row = $res->fetch_assoc()) {
											$dbId = htmlspecialchars($row['id']);
											$waCommunityId = htmlspecialchars($row['community_id']);
											$name = htmlspecialchars($row['community_name']);
											$inviteUrl = htmlspecialchars($row['invite_url']);
											 echo "<li class='list-group-item small py-1 px-2 community-item' style='cursor:pointer;' 
                                                data-community-id='{$dbId}' 
                                                data-wa-community-id='{$waCommunityId}' 
                                                data-invite-url='{$inviteUrl}'>
                                                {$name}
                                            </li>";
										}
										echo "</ul>";
									} else {
										echo "<p class='text-muted text-center mb-0 small'>No communities found.</p>";
									}
									?>
							</div>
						</div> 
					</div>
				</div>
            </div>
        </div>

<!-- Invite URL Modal -->
<div class="modal fade" id="inviteUrlModal" tabindex="-1" aria-labelledby="inviteUrlModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title" id="inviteUrlModalLabel">Community Invite URL</h5>
            <button type="button" class="btn btn-danger" data-bs-dismiss="modal" aria-label="Close">X</button>
        </div>
        <div class="modal-body">
            <input type="hidden" id="modalCommunityId">
			<input type="text" readonly class="form-control" id="inviteUrlInput" />
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-success" id="makeMeAdminBtn">Make Me Admin</button>
			<button type="button" class="btn btn-primary" id="copyInviteBtn">Copy URL</button>
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        </div>
        </div>
    </div>
</div>
<script>
    let inviteUrlModal;

    document.addEventListener('DOMContentLoaded', function () {
        inviteUrlModal = new bootstrap.Modal(document.getElementById('inviteUrlModal'));

        const inviteUrlInput = document.getElementById('inviteUrlInput');
        const copyInviteBtn = document.getElementById('copyInviteBtn');

        document.querySelectorAll('.community-item').forEach(function(item) {
            item.addEventListener('click', function() {
                const inviteUrl = this.getAttribute('data-invite-url');
                const communityId = this.getAttribute('data-community-id');

                if (inviteUrl && inviteUrl.trim() !== '') {
                    document.getElementById('modalCommunityId').value = communityId;
                    inviteUrlInput.value = inviteUrl;
                    inviteUrlModal.show();
                } else {
                    alert('Invite URL not available for this community.');
                }
            });
        });

        copyInviteBtn.addEventListener('click', function() {
            inviteUrlInput.select();
            inviteUrlInput.setSelectionRange(0, 99999);

            try {
                const successful = document.execCommand('copy');
                if (successful) {
                    copyInviteBtn.innerText = 'Copied!';
                    setTimeout(() => copyInviteBtn.innerText = 'Copy URL', 2000);
                } else {
                    alert('Failed to copy URL. Please copy manually.');
                }
            } catch (err) {
                alert('Copy command not supported. Please copy manually.');
            }
        });
    });

    document.getElementById('makeMeAdminBtn').addEventListener('click', makeMeAdmin);
    function makeMeAdmin() {
        const communityId = document.getElementById('modalCommunityId').value;
        // console.log("communityId to send:", communityId);
        // console.log("Sending community_id:", communityId, typeof communityId);
        if (!communityId) {
            alert("❌ Community ID missing!");
            return;
        }

        fetch('whatsapp-community-make-admin.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'community_id=' + encodeURIComponent(communityId)
        })
        .then(response => {
            if (!response.ok) throw new Error("HTTP " + response.status);
            return response.text();
        })
        .then(data => {
            alert(data);
        })
        .catch(error => {
            alert('Error: ' + error.message);
            console.error('Error:', error);
        });
    }
</script>
	<?php	include ('include/copyright.php');	?>
	</div>
	<?php	include ('footer.php');	?>