<?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 Group IC AMS</title>
 
	<?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 bg-success text-white"><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"><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 Group</h6>
							<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
								<div class="d-grid">
									<input type="text" class="form-control" id="group_name" name="group_name" placeholder="Enter group name..." required>
								</div>
								<div class="d-grid">
									<button type="submit" class="btn btn-primary mb-2" name='CreateGroup'>Create Group</button>
								</div>
							</form>
<?php
if(isset($_POST['CreateGroup']))
{	

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

$group_name = trim($_POST['group_name']);
$participants = [];
$fixedNumber = $fetch1['Official_Mobile_1'];
$cleanPhone = preg_replace('/\D/', '', $fixedNumber);

if ($cleanPhone && strlen($cleanPhone) >= 10 && strlen($cleanPhone) <= 15) {
    if (strlen($cleanPhone) === 12 && strpos($cleanPhone, '91') === 0) {
        $participants[] = $cleanPhone;
    } else {
       $participants[] = '91' . $cleanPhone;
    }
}
 
if (count($participants) === 0) {
    die("❌ Error: No valid participants found.");
}

$payload = [
    'subject'      => $group_name,
    'participants' => $participants
];

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

$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);

$data = json_decode($response, true);

if ($http_code !== 200 || empty($data['id'])) {
    die("❌ Error: Failed to create group. API response:<br><pre>" . print_r($data, true) . "</pre>");
}

$group_id = $data['id'];

$invite_url = rtrim(API_BASE_URL, '/') . "/groups/$group_id/invite";
$ch = curl_init($invite_url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => [
        'Content-Type: application/json',
        'Authorization: Bearer ' . API_TOKEN
    ],
    CURLOPT_SSL_VERIFYPEER => false
]);
$invite_response = curl_exec($ch);
$http_code_invite = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$invite_data = json_decode($invite_response, true);
$empid = $fetch1['empid'] ?? '';
$Employee_Full_Name = $fetch1['Employee_Full_Name'] ?? '';
$Official_Mobile_1 = $fetch1['Official_Mobile_1'] ?? '';
if ($http_code_invite !== 200 || empty($invite_data['invite_code'])) {
    die("❌ Error: Failed to fetch group invite code. API response:<br><pre>" . print_r($invite_data, true) . "</pre>");
}

$invite_code = $invite_data['invite_code'];

$stmt = $conwhatsapp->prepare("INSERT INTO `groups` (group_id, group_name, invite_code, empid, Employee_Full_Name, Official_Mobile_1) VALUES (?, ?, ?, ?, ?, ?)");

if (!$stmt) {
    die("❌ DB Error: " . $conwhatsapp->error);
}
$stmt->bind_param("ssssss", $group_id, $group_name, $invite_code, $empid, $Employee_Full_Name, $Official_Mobile_1);
$stmt->execute();
$stmt->close();
	$_SESSION['success_msg'] = "<h6>✅ Group created successfully!</h6><h6>$group_name</h6>";
	echo "<script>window.location.href='whatsapp-group-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 Group List</h6>
                            <div class="text-start">
                                <?php
                                $result = $conwhatsapp->query("SELECT id, group_id, group_name, invite_code FROM `groups` ORDER BY id DESC");
                                if ($result && $result->num_rows > 0) {
                                    echo "<ul class='list-group list-group-flush'>";
                                    while ($row = $result->fetch_assoc()) {
                                        $dbId = htmlspecialchars($row['id']);
                                        $waGroupId = htmlspecialchars($row['group_id']);
                                        $groupName = htmlspecialchars($row['group_name']);
                                        $inviteUrl = "https://chat.whatsapp.com/" . htmlspecialchars($row['invite_code']);

                                        echo "<li class='list-group-item small py-1 px-2' style='cursor:pointer;' 
                                            data-group-id='{$dbId}' 
                                            data-wa-group-id='{$waGroupId}' 
                                            data-invite-url='{$inviteUrl}'>
                                            {$groupName}
                                        </li>";
                                    }
                                    echo "</ul>";
                                } else {
                                    echo "<p class='text-muted text-center mb-0 small'>No groups found.</p>";
                                }
                                ?>
                            </div>
                        </div>
                    </div>
				</div>
            </div>
        </div>
<div class="modal fade" id="inviteModal" tabindex="-1" aria-labelledby="inviteModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="inviteModalLabel">Group 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="modalGroupId">
                <input type="text" id="inviteUrlInput" class="form-control" readonly>
            </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>
  document.addEventListener('DOMContentLoaded', function () {
    var inviteModal = new bootstrap.Modal(document.getElementById('inviteModal'));
    function showInviteModal(element) {
      var groupId = element.getAttribute('data-group-id');
      var inviteUrl = element.getAttribute('data-invite-url');
      document.getElementById('modalGroupId').value = groupId;
      document.getElementById('inviteUrlInput').value = inviteUrl;
      console.log('Modal triggered for Group ID:', groupId);
      console.log('Invite URL:', inviteUrl);

      inviteModal.show();
    }
    document.querySelectorAll('.list-group-item').forEach(function(item) {
      item.addEventListener('click', function() {
        showInviteModal(this);
      });
    });
    function copyInviteUrl() {
      var input = document.getElementById('inviteUrlInput');
      input.select();
      input.setSelectionRange(0, 99999);

      try {
        var successful = document.execCommand('copy');
        if (successful) {
          alert('Copied invite URL to clipboard!');
        } else {
          alert('Unable to copy. Please copy manually.');
        }
      } catch (err) {
        alert('Unsupported browser. Please copy manually.');
      }
    }
    document.getElementById('copyInviteBtn').addEventListener('click', copyInviteUrl);

    window.makeMeAdmin = function() {
      const groupId = document.getElementById('modalGroupId').value;
      console.log("Group ID to send:", groupId);
		console.log("Sending group_id:", groupId, typeof groupId);
		
      if (!groupId) {
        alert("❌ Group ID missing!");
        return;
      }

      fetch('whatsapp-group-make-admin.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'group_id=' + encodeURIComponent(groupId)
      })
      .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);
      });
    }

    document.getElementById('makeMeAdminBtn').addEventListener('click', makeMeAdmin);
  });
</script>


		<?php	include ('include/copyright.php');	?>
	</div>
	
	<?php	include ('footer.php');	?>