<?php
// ফায়ারবেস ফাইল লোকেশন
$serviceAccountFile = 'noti.json';

// POST Request হ্যান্ডেল (যখন সেন্ড বাটনে ক্লিক করা হবে)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header("Content-Type: application/json; charset=UTF-8");

    $title   = isset($_POST['title']) ? trim($_POST['title']) : '';
    $body    = isset($_POST['body']) ? trim($_POST['body']) : '';
    $image   = isset($_POST['image']) ? trim($_POST['image']) : '';
    $extra   = isset($_POST['extra']) ? trim($_POST['extra']) : '';
    $target  = isset($_POST['target']) ? trim($_POST['target']) : 'all'; 
    $fcmId   = isset($_POST['fcmId']) ? trim($_POST['fcmId']) : '';

    if (empty($title) || empty($body)) {
        echo json_encode(["status" => "error", "message" => "Title and Body are required!"]); exit;
    }
    if ($target === 'specific' && empty($fcmId)) {
        echo json_encode(["status" => "error", "message" => "FCM Token is required for specific user!"]); exit;
    }
    if (!file_exists($serviceAccountFile)) {
        echo json_encode(["status" => "error", "message" => "Error: noti.json file not found in the server!"]); exit;
    }

    // Base64Url এনকোড
    function base64url_encode($data) { return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); }

    // Access Token জেনারেট
    function getAccessToken($jsonFilePath) {
        $credentials = json_decode(file_get_contents($jsonFilePath), true);
        if (!$credentials || !isset($credentials['private_key'])) return false;

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

        $header = json_encode(['alg' => 'RS256', 'typ' => 'JWT']);
        $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
        ]);

        $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($response, true);
        return isset($responseData['access_token']) ? $responseData['access_token'] : false;
    }

    $accessToken = getAccessToken($serviceAccountFile);
    if (!$accessToken) {
        echo json_encode(["status" => "error", "message" => "Failed to get access token from Google!"]); exit;
    }

    $credentials = json_decode(file_get_contents($serviceAccountFile), true);
    $projectId = $credentials['project_id'];
    $url = "https://fcm.googleapis.com/v1/projects/" . $projectId . "/messages:send";

    // Data Payload (Android App এর মত হুবহু)
    $notificationMap = [
        "title" => $title,
        "body"  => $body,
        "image" => $image,
        "extra" => $extra
    ];

    $message = [];
    if ($target === 'all') {
        $message['topic'] = "ttt"; // আপনার জাভা অ্যাপের Topic "User"
    } else {
        $message['token'] = $fcmId;
    }
    $message['data'] = $notificationMap;

    $postData = json_encode(["message" => $message]);

    $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; 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 = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode == 200) {
        echo json_encode(["status" => "success", "message" => "🔥 Notification Sent Successfully!"]);
    } else {
        $err = json_decode($result, true);
        echo json_encode(["status" => "error", "message" => "Error: " . ($err['error']['message'] ?? 'Unknown Error')]);
    }
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Send Notification</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #6366f1;
            --primary-hover: #4f46e5;
            --bg-body: #f8fafc;
            --card-bg: #ffffff;
            --text-dark: #0f172a;
            --text-muted: #64748b;
        }
        body {
            font-family: 'Plus Jakarta Sans', sans-serif;
            background: var(--bg-body);
            color: var(--text-dark);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .notice-card {
            background: var(--card-bg);
            border-radius: 24px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.05);
            width: 100%;
            max-width: 500px;
            padding: 35px 30px;
            border: 1px solid rgba(0,0,0,0.03);
            position: relative;
            overflow: hidden;
        }
        .header-section {
            text-align: center;
            margin-bottom: 30px;
        }
        .header-section .icon-box {
            width: 60px; height: 60px;
            background: #eef2ff;
            color: var(--primary);
            border-radius: 18px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 26px;
            margin-bottom: 15px;
            transform: rotate(-5deg);
        }
        .header-section h3 {
            font-weight: 800;
            font-size: 24px;
            margin: 0;
            letter-spacing: -0.5px;
        }
        .header-section p { color: var(--text-muted); font-size: 14px; margin-top: 5px; }

        /* Custom Form Controls */
        .form-control {
            background: #f1f5f9;
            border: 2px solid transparent;
            border-radius: 14px;
            padding: 14px 18px;
            font-size: 15px;
            font-weight: 500;
            color: var(--text-dark);
            transition: all 0.3s ease;
        }
        .form-control:focus {
            background: #fff;
            border-color: var(--primary);
            box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.1);
        }
        .form-label {
            font-size: 13px;
            font-weight: 700;
            color: var(--text-muted);
            margin-bottom: 6px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        /* Toggle Button */
        .img-toggle-btn {
            background: transparent;
            border: none;
            color: var(--primary);
            font-weight: 700;
            font-size: 13px;
            padding: 0;
            margin-bottom: 10px;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            transition: color 0.3s;
        }
        .img-toggle-btn:hover { color: var(--primary-hover); }
        .img-toggle-btn.remove { color: #ef4444; }
        .img-input-group { display: none; }

        /* Target Selector */
        .target-selector {
            display: flex;
            background: #f1f5f9;
            border-radius: 14px;
            padding: 6px;
            margin-bottom: 20px;
        }
        .target-selector label {
            flex: 1;
            text-align: center;
            padding: 10px;
            border-radius: 10px;
            font-weight: 600;
            font-size: 14px;
            cursor: pointer;
            color: var(--text-muted);
            transition: all 0.3s;
            margin: 0;
        }
        .target-selector input[type="radio"] { display: none; }
        .target-selector input[type="radio"]:checked + label {
            background: #fff;
            color: var(--primary);
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
        }
        #fcmTokenGroup { display: none; }

        /* Submit Button */
        .btn-send {
            background: linear-gradient(135deg, var(--primary) 0%, #8b5cf6 100%);
            color: #fff;
            border: none;
            border-radius: 16px;
            padding: 16px;
            width: 100%;
            font-size: 16px;
            font-weight: 700;
            margin-top: 10px;
            box-shadow: 0 10px 20px rgba(99, 102, 241, 0.3);
            transition: all 0.3s;
        }
        .btn-send:hover {
            transform: translateY(-2px);
            box-shadow: 0 15px 25px rgba(99, 102, 241, 0.4);
        }
        .btn-send:active { transform: translateY(0); }

        /* Loader inside button */
        .btn-send .spinner-border {
            width: 1.2rem; height: 1.2rem;
            display: none;
        }
        .btn-send.loading .spinner-border { display: inline-block; }
        .btn-send.loading .btn-text { display: none; }

        /* Custom Toast */
        .custom-toast {
            position: fixed;
            top: 20px; right: 20px;
            background: #fff;
            padding: 16px 24px;
            border-radius: 16px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.1);
            display: flex;
            align-items: center;
            gap: 12px;
            font-weight: 600;
            transform: translateX(120%);
            transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            z-index: 9999;
        }
        .custom-toast.show { transform: translateX(0); }
        .toast-success .icon { color: #10b981; font-size: 20px; }
        .toast-error .icon { color: #ef4444; font-size: 20px; }
    </style>
</head>
<body>

<div class="custom-toast" id="myToast">
    <div class="icon"><i class="fas fa-check-circle" id="toastIcon"></i></div>
    <div id="toastMessage">Notification Sent!</div>
</div>

<div class="notice-card">
    <div class="header-section">
        <div class="icon-box"><i class="fas fa-paper-plane"></i></div>
        <h3>Push Notification</h3>
        <p>Broadcast messages to your users instantly</p>
    </div>

    <form id="noticeForm">
        <!-- Target Selection -->
        <div class="target-selector">
            <input type="radio" name="target" id="targetAll" value="all" checked>
            <label for="targetAll"><i class="fas fa-users me-2"></i>All Users</label>
            
            <input type="radio" name="target" id="targetSpecific" value="specific">
            <label for="targetSpecific"><i class="fas fa-user me-2"></i>Specific User</label>
        </div>

        <div class="mb-3" id="fcmTokenGroup">
            <label class="form-label">User FCM Token</label>
            <input type="text" class="form-control" id="fcmId" placeholder="Paste user token here...">
        </div>

        <!-- Inputs -->
        <div class="mb-3">
            <label class="form-label">Notification Title</label>
            <input type="text" class="form-control" id="title" placeholder="Enter title" required>
        </div>

        <div class="mb-3">
            <label class="form-label">Message Body</label>
            <textarea class="form-control" id="body" rows="3" placeholder="Type your message..." required></textarea>
        </div>

        <!-- Image Toggle Logic -->
        <button type="button" class="img-toggle-btn" id="toggleImgBtn">
            <i class="fas fa-image"></i> <span>ADD IMAGE</span>
        </button>
        
        <div class="mb-3 img-input-group" id="imgGroup">
            <input type="url" class="form-control" id="image" placeholder="https://example.com/image.jpg">
        </div>

        <div class="mb-4">
            <label class="form-label">Extra Data (Optional)</label>
            <input type="text" class="form-control" id="extra" placeholder="Action links or extra info">
        </div>

        <!-- Submit -->
        <button type="submit" class="btn-send" id="sendBtn">
            <span class="btn-text">Send Notification <i class="fas fa-arrow-right ms-2"></i></span>
            <div class="spinner-border text-light" role="status"></div>
        </button>
    </form>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
    $(document).ready(function() {
        // Toggle Image Input
        $('#toggleImgBtn').on('click', function() {
            const btn = $(this);
            const imgGroup = $('#imgGroup');
            const span = btn.find('span');
            
            if(imgGroup.is(':visible')) {
                imgGroup.slideUp(200);
                $('#image').val(''); // Clear image URL when removed
                span.text('ADD IMAGE');
                btn.removeClass('remove');
            } else {
                imgGroup.slideDown(200);
                span.text('REMOVE IMG');
                btn.addClass('remove');
            }
        });

        // Toggle Target Selector
        $('input[name="target"]').on('change', function() {
            if($(this).val() === 'specific') {
                $('#fcmTokenGroup').slideDown(200);
                $('#fcmId').attr('required', true);
            } else {
                $('#fcmTokenGroup').slideUp(200);
                $('#fcmId').removeAttr('required').val('');
            }
        });

        // Show Toast Function
        function showToast(message, isSuccess) {
            const toast = $('#myToast');
            $('#toastMessage').text(message);
            
            if(isSuccess) {
                toast.removeClass('toast-error').addClass('toast-success');
                $('#toastIcon').attr('class', 'fas fa-check-circle');
            } else {
                toast.removeClass('toast-success').addClass('toast-error');
                $('#toastIcon').attr('class', 'fas fa-exclamation-circle');
            }

            toast.addClass('show');
            setTimeout(() => toast.removeClass('show'), 3500);
        }

        // Handle Form Submit
        $('#noticeForm').on('submit', function(e) {
            e.preventDefault();
            const btn = $('#sendBtn');
            btn.addClass('loading').prop('disabled', true);

            // Prepare Data
            const formData = {
                target: $('input[name="target"]:checked').val(),
                fcmId: $('#fcmId').val(),
                title: $('#title').val(),
                body: $('#body').val(),
                image: $('#image').val(),
                extra: $('#extra').val()
            };

            // Send POST Request to itself
            $.post('', formData, function(response) {
                btn.removeClass('loading').prop('disabled', false);
                if(response.status === 'success') {
                    showToast(response.message, true);
                    $('#noticeForm')[0].reset();
                    if($('#imgGroup').is(':visible')) $('#toggleImgBtn').click(); // Auto hide image
                } else {
                    showToast(response.message, false);
                }
            }).fail(function() {
                btn.removeClass('loading').prop('disabled', false);
                showToast("Server Connection Error!", false);
            });
        });
    });
</script>

</body>
</html>