<?php
include '../config.php';
include 'whatsapp-api-config.php';

@session_start();

$user_id1 = isset($_SESSION['user_id1']) ? $_SESSION['user_id1'] : null;

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo "Only POST allowed.";
    exit;
}

if (!isset($_POST['community_id']) || !filter_var($_POST['community_id'], FILTER_VALIDATE_INT)) {
    http_response_code(422);
    echo "Community ID is missing or invalid.";
    exit;
}

$communityId = (int) $_POST['community_id'];

$sel1 = mysqli_query($conn, "SELECT Official_Mobile_1 FROM hr_dump WHERE empid = '" . mysqli_real_escape_string($conn, $user_id1) . "'");
$fetch1 = mysqli_fetch_array($sel1);

if (!$fetch1 || empty($fetch1['Official_Mobile_1'])) {
    http_response_code(422);
    echo "Phone number not found for the employee.";
    exit;
}

$rawPhone = preg_replace('/\D/', '', $fetch1['Official_Mobile_1']);
$phoneForApi = (strlen($rawPhone) === 10) ? '91' . $rawPhone : $rawPhone;

$stmt = $conwhatsapp->prepare("SELECT community_id, community_name FROM `communities` WHERE id = ?");
if (!$stmt) {
    http_response_code(500);
    echo "Database error: failed to prepare statement.";
    exit;
}

$stmt->bind_param("i", $communityId);
if (!$stmt->execute()) {
    http_response_code(500);
    echo "Database error: failed to execute statement.";
    exit;
}

$result = $stmt->get_result();
$community = $result->fetch_assoc();
$stmt->close();

if (!$community) {
    http_response_code(422);
    echo "Invalid community selected.";
    exit;
}

$wa_community_id = $community['community_id'];
$community_name = $community['community_name'];

if (substr($wa_community_id, -5) !== '@g.us') {
    $wa_community_id .= '@g.us';
}

$payload = ['participants' => [$phoneForApi]];
$url = "https://gate.whapi.cloud/communities/" . urlencode($wa_community_id) . "/admins";

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => 'PATCH',
    CURLOPT_POSTFIELDS => json_encode($payload),
    CURLOPT_HTTPHEADER => [
        'Accept: application/json',
        'Authorization: Bearer ' . API_TOKEN,
        'Content-Type: application/json',
    ],
    CURLOPT_SSL_VERIFYPEER => false,
]);

$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

$data = json_decode($response, true);

if ($http_code !== 200) {
    http_response_code($http_code);
    echo "API call failed (Status $http_code): " . ($error ?: json_encode($data));
    exit;
}

if (isset($data['error'])) {
    http_response_code(500);
    echo "WhatsApp API error: " . $data['error']['message'];
    exit;
}

$update_stmt = $conwhatsapp->prepare("UPDATE `communities` SET AdminStatus = 'Active', AdminStatusDate = NOW() WHERE community_id = ?");
if (!$update_stmt) {
    http_response_code(500);
    echo "Database error: failed to prepare update statement.";
    exit;
}

$update_stmt->bind_param("s", $wa_community_id);
if (!$update_stmt->execute()) {
    http_response_code(500);
    echo "Database error: failed to update AdminStatus.";
    exit;
}

$update_stmt->close();

http_response_code(200);
echo "✅ You have been promoted to admin in the community '$community_name'";
exit;
?>
