<?php
require_once "config.php";

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

date_default_timezone_set("Asia/Dhaka");

if (!isset($conn) || !($conn instanceof mysqli)) {
    die("Database connection not available.");
}
$conn->set_charset("utf8mb4");

if (empty($_SESSION['auth_logged_in'])) {
    header("Location: login.php");
    exit;
}

$can_send_notification = false;
$username = (string)($_SESSION['auth_username'] ?? '');
$role = (string)($_SESSION['auth_role'] ?? '');

if ($role === 'admin') {
    $can_send_notification = true;
} elseif ($role === 'permission') {
    $sql = "SELECT notification_send FROM `Zabbar_Admin_Permission` WHERE username = ? LIMIT 1";
    $stmt = $conn->prepare($sql);
    if ($stmt) {
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($row = $res->fetch_assoc()) {
            $can_send_notification = (strtolower(trim((string)($row['notification_send'] ?? ''))) === 'yes');
        }
        $stmt->close();
    }
}

$fetched_username = '';
$fetched_fcm_token = '';
$has_url_user = false;

if (isset($_GET['username']) && trim((string)$_GET['username']) !== '') {
    $search_user = trim((string)$_GET['username']);
    $u_sql = "SELECT username, fcm_key FROM users WHERE username = ? LIMIT 1";
    $u_stmt = $conn->prepare($u_sql);
    if ($u_stmt) {
        $u_stmt->bind_param("s", $search_user);
        $u_stmt->execute();
        $u_res = $u_stmt->get_result();
        if ($u_row = $u_res->fetch_assoc()) {
            $fetched_username = (string)($u_row['username'] ?? '');
            $fetched_fcm_token = (string)($u_row['fcm_key'] ?? '');
            $has_url_user = true;
        }
        $u_stmt->close();
    }
}

$message = '';

function e($value): string {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function base64url_encode($data): string {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function getAccessToken($jsonFilePath) {
    $credentials = json_decode(@file_get_contents($jsonFilePath), true);
    if (!$credentials || empty($credentials['private_key']) || empty($credentials['client_email'])) return false;

    $clientEmail = $credentials['client_email'];
    $privateKey  = $credentials['private_key'];

    $header = json_encode(['alg' => 'RS256', 'typ' => 'JWT'], JSON_UNESCAPED_SLASHES);
    $now = time();
    $payload = json_encode([
        'iss'   => $clientEmail,
        'scope' => 'https://www.googleapis.com/auth/cloud-platform',
        'aud'   => 'https://oauth2.googleapis.com/token',
        'exp'   => $now + 3600,
        'iat'   => $now
    ], JSON_UNESCAPED_SLASHES);

    $unsignedJwt = base64url_encode($header) . "." . base64url_encode($payload);
    $signature = '';
    openssl_sign($unsignedJwt, $signature, $privateKey, OPENSSL_ALGO_SHA256);
    $jwt = $unsignedJwt . "." . base64url_encode($signature);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://oauth2.googleapis.com/token');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'assertion'  => $jwt
    ]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    curl_close($ch);

    $responseData = json_decode((string)$response, true);
    return $responseData['access_token'] ?? false;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!$can_send_notification) {
        $message = "<div class='alert error'>Access Denied: You do not have permission to send notifications.</div>";
    } else {
        $target_type  = ($_POST['target_type'] ?? 'all');
        $target_value = trim((string)($_POST['target_value'] ?? ''));
        $payload_type = ($_POST['payload_type'] ?? 'standard');

        $title       = trim((string)($_POST['title'] ?? ''));
        $body        = trim((string)($_POST['body'] ?? ''));
        $custom_json = trim((string)($_POST['custom_json'] ?? ''));

        $serviceAccountFile = 'noti.json';

        if (($target_type === 'token' || $target_type === 'topic') && $target_value === '') {
            $message = "<div class='alert error'>Target Value is required.</div>";
        } elseif (!file_exists($serviceAccountFile)) {
            $message = "<div class='alert error'>Error: noti.json file not found.</div>";
        } else {
            $accessToken = getAccessToken($serviceAccountFile);

            if (!$accessToken) {
                $message = "<div class='alert error'>Failed to generate access token from Google.</div>";
            } else {
                $credentials = json_decode(file_get_contents($serviceAccountFile), true);
                $projectId = $credentials['project_id'] ?? '';
                if ($projectId === '') {
                    $message = "<div class='alert error'>Invalid service account file.</div>";
                } else {
                    $url = "https://fcm.googleapis.com/v1/projects/" . $projectId . "/messages:send";

                    $messagePayload = [];

                    if ($target_type === 'all') {
                        $messagePayload['topic'] = "ttt";
                    } elseif ($target_type === 'topic') {
                        $messagePayload['topic'] = $target_value;
                    } else {
                        $messagePayload['token'] = $target_value;
                    }

                    $is_valid = true;

                    if ($payload_type === 'custom') {
                        if ($custom_json === '') {
                            $message = "<div class='alert error'>Custom JSON cannot be empty.</div>";
                            $is_valid = false;
                        } else {
                            $decoded = json_decode($custom_json, true);
                            if (json_last_error() !== JSON_ERROR_NONE) {
                                $message = "<div class='alert error'>Invalid JSON format. Please check syntax.</div>";
                                $is_valid = false;
                            } else {
                                $messagePayload = array_merge($decoded, $messagePayload);
                            }
                        }
                    } else {
                        if ($title === '' || $body === '') {
                            $message = "<div class='alert error'>Title and Message Body are required.</div>";
                            $is_valid = false;
                        } else {
                            $messagePayload['data'] = [
                                "title" => $title,
                                "body"  => $body,
                                "image" => "",
                                "extra" => ""
                            ];
                        }
                    }

                    if ($is_valid) {
                        $postData = json_encode(["message" => $messagePayload], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

                        $ch = curl_init();
                        curl_setopt($ch, CURLOPT_URL, $url);
                        curl_setopt($ch, CURLOPT_POST, true);
                        curl_setopt($ch, CURLOPT_HTTPHEADER, [
                            'Authorization: Bearer ' . $accessToken,
                            'Content-Type: application/json; charset=UTF-8'
                        ]);
                        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

                        $result = curl_exec($ch);
                        $httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
                        curl_close($ch);

                        if ($httpCode === 200) {
                            $message = "<div class='alert success'>
                                <svg viewBox='0 0 24 24' width='20' height='20' stroke='currentColor' stroke-width='2' fill='none' stroke-linecap='round' stroke-linejoin='round'><polyline points='20 6 9 17 4 12'></polyline></svg>
                                Notification sent successfully via FCM.
                            </div>";
                        } else {
                            $err = json_decode((string)$result, true);
                            $errMsg = $err['error']['message'] ?? 'Unknown API Error';
                            $message = "<div class='alert error'>Error: " . e($errMsg) . "</div>";
                        }
                    }
                }
            }
        }
    }
}

$default_custom_json = '{
  "data": {
    "title": "Welcome {Player Name}",
    "body": "প্রিয় {Player Name}, আপনার জয়েনকৃত ম্যাচ",
    "source_url": "https://zabbar.com/my.php?email={email}",
    "activity": "ZabbarHomeActivity"
  }
}';

require_once "header.php";
?>

<style>
    :root{
        --bg:#f4f7fb;
        --card:#ffffff;
        --text:#102033;
        --muted:#5f6f82;
        --line:#dbe5f0;
        --accent:#2563eb;
        --accent2:#7c3aed;
        --shadow:0 20px 60px rgba(16, 32, 51, .08);
        --radius:22px;
    }

    .page-shell{
        width:100%;
        padding:14px;
    }

    .container{
        width:min(760px, 100%);
        margin:0 auto;
        display:flex;
        flex-direction:column;
        gap:16px;
    }

    .card{
        width:100%;
        background:rgba(255,255,255,.96);
        border:1px solid var(--line);
        border-radius:var(--radius);
        box-shadow:var(--shadow);
        overflow:hidden;
    }

    .card-head{
        padding:18px 18px 14px;
        border-bottom:1px solid var(--line);
    }

    .card-head h1{
        font-size:22px;
        line-height:1.2;
        margin:0;
        background:linear-gradient(135deg,var(--accent),var(--accent2));
        -webkit-background-clip:text;
        -webkit-text-fill-color:transparent;
    }

    .card-head p{
        margin-top:6px;
        color:var(--muted);
        font-size:13px;
        line-height:1.6;
    }

    .body-content{
        padding:18px;
    }

    .alert{
        display:flex;
        align-items:flex-start;
        gap:10px;
        padding:14px 15px;
        border-radius:14px;
        margin-bottom:16px;
        font-size:14px;
        line-height:1.6;
        font-weight:600;
    }
    .alert.success{
        background:#f0fdf4;
        border:1px solid #bbf7d0;
        color:#166534;
    }
    .alert.error{
        background:#fef2f2;
        border:1px solid #fecaca;
        color:#991b1b;
    }

    .section-title{
        font-size:12px;
        font-weight:800;
        color:var(--muted);
        text-transform:uppercase;
        letter-spacing:.08em;
        margin:6px 0 10px;
    }

    .target-options,
    .payload-options{
        display:grid;
        grid-template-columns:repeat(3,minmax(0,1fr));
        gap:10px;
        margin-bottom:14px;
    }

    .payload-options{
        grid-template-columns:repeat(2,minmax(0,1fr));
    }

    .target-option input{
        display:none;
    }

    .target-option label{
        display:flex;
        align-items:center;
        justify-content:center;
        min-height:46px;
        padding:10px;
        border:1px solid var(--line);
        border-radius:14px;
        cursor:pointer;
        font-size:14px;
        font-weight:700;
        color:var(--muted);
        background:#fff;
        transition:.2s ease;
        user-select:none;
        text-align:center;
    }

    .target-option input:checked + label{
        background:rgba(37,99,235,.06);
        border-color:var(--accent);
        color:var(--accent);
        box-shadow:0 0 0 4px rgba(37,99,235,.08);
    }

    .field{
        display:flex;
        flex-direction:column;
        gap:7px;
        margin-bottom:14px;
    }

    .field label{
        font-size:13px;
        font-weight:800;
        color:#334155;
    }

    input[type="text"], textarea{
        width:100%;
        border:1px solid var(--line);
        background:#fff;
        color:var(--text);
        border-radius:14px;
        padding:13px 14px;
        font-size:15px;
        outline:none;
        transition:.2s ease;
        font-family:inherit;
    }

    textarea{
        resize:vertical;
        min-height:100px;
    }

    .json-textarea{
        font-family:ui-monospace, SFMono-Regular, Menlo, monospace;
        font-size:13px;
        min-height:180px;
        background:#f8fafc;
    }

    input:focus, textarea:focus{
        border-color:rgba(37,99,235,.65);
        box-shadow:0 0 0 4px rgba(37,99,235,.10);
        background:#fff;
    }

    .btn{
        width:100%;
        border:none;
        border-radius:14px;
        padding:14px 16px;
        font-size:15px;
        font-weight:800;
        color:#fff;
        cursor:pointer;
        background:linear-gradient(135deg, var(--accent), var(--accent2));
        box-shadow:0 14px 28px rgba(37,99,235,.16);
        transition:.2s ease;
        margin-top:6px;
    }

    .btn:hover{
        transform:translateY(-2px);
        box-shadow:0 16px 32px rgba(37,99,235,.20);
    }

    .hidden{
        display:none !important;
    }

    .no-access{
        text-align:center;
        padding:28px 18px;
        background:#fef2f2;
        border:1px dashed #f87171;
        border-radius:18px;
        color:#991b1b;
        font-weight:700;
        font-size:15px;
        line-height:1.6;
    }

    @media (max-width:768px){
        .page-shell{
            padding:10px;
        }

        .container{
            width:100%;
            gap:12px;
        }

        .card-head{
            padding:16px 14px 12px;
        }

        .card-head h1{
            font-size:18px;
        }

        .body-content{
            padding:14px;
        }

        .target-options{
            grid-template-columns:1fr;
        }

        .payload-options{
            grid-template-columns:1fr;
        }

        .target-option label{
            min-height:44px;
        }

        input[type="text"], textarea{
            font-size:14px;
        }

        .json-textarea{
            min-height:160px;
        }
    }
</style>

<div class="page-shell">
    <div class="container">
        <div class="card">
            <div class="card-head">
                <h1>Send Notification</h1>
                <p>Push standard or custom FCM payloads without wasting screen space.</p>
            </div>

            <div class="body-content">
                <?php if ($message !== '') echo $message; ?>

                <?php if ($can_send_notification): ?>
                    <form method="post" autocomplete="off">
                        <div class="section-title">Target</div>
                        <div class="target-options">
                            <div class="target-option">
                                <input type="radio" id="tgt_all" name="target_type" value="all" <?= !$has_url_user ? 'checked' : ''; ?>>
                                <label for="tgt_all">All Users</label>
                            </div>
                            <div class="target-option">
                                <input type="radio" id="tgt_token" name="target_type" value="token" <?= $has_url_user ? 'checked' : ''; ?>>
                                <label for="tgt_token">Token User</label>
                            </div>
                            <div class="target-option">
                                <input type="radio" id="tgt_topic" name="target_type" value="topic">
                                <label for="tgt_topic">Topic</label>
                            </div>
                        </div>

                        <div id="target_value_wrapper" class="field <?= !$has_url_user ? 'hidden' : ''; ?>">
                            <label id="target_value_label"><?= $has_url_user ? 'Target FCM Token (User: ' . e($fetched_username) . ')' : 'Target Value' ?></label>
                            <input type="text" id="target_value" name="target_value" value="<?= e($fetched_fcm_token) ?>" placeholder="<?= $has_url_user ? 'Device token...' : 'Enter value...' ?>">
                        </div>

                        <div class="section-title">Payload Style</div>
                        <div class="payload-options">
                            <div class="target-option">
                                <input type="radio" id="pt_standard" name="payload_type" value="standard" checked>
                                <label for="pt_standard">Standard</label>
                            </div>
                            <div class="target-option">
                                <input type="radio" id="pt_custom" name="payload_type" value="custom">
                                <label for="pt_custom">Custom JSON</label>
                            </div>
                        </div>

                        <div id="standard_fields">
                            <div class="field">
                                <label>Notification Title</label>
                                <input type="text" name="title" id="inp_title" placeholder="Enter title">
                            </div>

                            <div class="field">
                                <label>Notification Message</label>
                                <textarea name="body" id="inp_body" placeholder="Enter message body"></textarea>
                            </div>
                        </div>

                        <div id="custom_fields" class="hidden">
                            <div class="field">
                                <label>Custom JSON</label>
                                <textarea name="custom_json" id="inp_custom_json" class="json-textarea" placeholder="Enter JSON payload"><?= e($default_custom_json) ?></textarea>
                            </div>
                        </div>

                        <button type="submit" class="btn" id="submit_btn">Push Notification</button>
                    </form>
                <?php else: ?>
                    <div class="no-access">
                        Access Denied: You do not have permission to send notifications.
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
const hasUrlUser = <?= $has_url_user ? 'true' : 'false'; ?>;
const urlUsername = <?= json_encode($fetched_username, JSON_UNESCAPED_UNICODE); ?>;
const urlToken = <?= json_encode($fetched_fcm_token, JSON_UNESCAPED_UNICODE); ?>;

function setTargetField(type) {
    const wrapper = document.getElementById('target_value_wrapper');
    const input = document.getElementById('target_value');
    const label = document.getElementById('target_value_label');

    if (!wrapper || !input || !label) return;

    if (type === 'all') {
        wrapper.classList.add('hidden');
        input.removeAttribute('required');
        input.value = '';
        input.placeholder = 'Enter value...';
    } else if (type === 'token') {
        wrapper.classList.remove('hidden');
        label.textContent = hasUrlUser ? ('Target FCM Token (User: ' + urlUsername + ')') : 'Target FCM Token';
        input.placeholder = 'Enter device token...';
        input.value = hasUrlUser ? urlToken : '';
        input.setAttribute('required', 'required');
    } else if (type === 'topic') {
        wrapper.classList.remove('hidden');
        label.textContent = 'Target Topic Name';
        input.placeholder = 'Enter topic name (e.g. offers, updates)';
        input.value = '';
        input.setAttribute('required', 'required');
    }
}

function setPayload(type) {
    const standardFields = document.getElementById('standard_fields');
    const customFields = document.getElementById('custom_fields');
    const titleInput = document.getElementById('inp_title');
    const bodyInput = document.getElementById('inp_body');
    const customJsonInput = document.getElementById('inp_custom_json');
    const submitBtn = document.getElementById('submit_btn');

    if (!standardFields || !customFields || !titleInput || !bodyInput || !customJsonInput || !submitBtn) return;

    if (type === 'standard') {
        standardFields.classList.remove('hidden');
        customFields.classList.add('hidden');
        titleInput.setAttribute('required', 'required');
        bodyInput.setAttribute('required', 'required');
        customJsonInput.removeAttribute('required');
        submitBtn.textContent = 'Push Notification';
        submitBtn.style.background = 'linear-gradient(135deg, var(--accent), var(--accent2))';
    } else {
        standardFields.classList.add('hidden');
        customFields.classList.remove('hidden');
        titleInput.removeAttribute('required');
        bodyInput.removeAttribute('required');
        customJsonInput.setAttribute('required', 'required');
        submitBtn.textContent = 'Send CUSTOM Payload';
        submitBtn.style.background = 'linear-gradient(135deg, #10b981, #059669)';
    }
}

document.querySelectorAll('input[name="target_type"]').forEach(radio => {
    radio.addEventListener('change', function () {
        setTargetField(this.value);
    });
});

document.querySelectorAll('input[name="payload_type"]').forEach(radio => {
    radio.addEventListener('change', function () {
        setPayload(this.value);
    });
});

const checkedTarget = document.querySelector('input[name="target_type"]:checked');
if (checkedTarget) setTargetField(checkedTarget.value);

const checkedPayload = document.querySelector('input[name="payload_type"]:checked');
if (checkedPayload) setPayload(checkedPayload.value);
</script>