<?php 
// নোটিফিকেশন ম্যানেজমেন্ট পেজ (FCM HTTP v1)
include 'header.php'; 

if(isset($_POST['send_notification'])) {
    $title = $_POST['notif_title'];
    $message = $_POST['notif_msg'];
    $actionUrl = $_POST['action_url'];
    $imageUrl = $_POST['image_url'];

    // ১. Service Account JSON ফাইল থেকে ডাটা নেওয়া
    $jsonFile = 'service-account.json'; 
    if (!file_exists($jsonFile)) {
        die("<script>alert('Error: service-account.json file not found!'); window.history.back();</script>");
    }
    
    $data = json_decode(file_get_contents($jsonFile), true);
    $client_email = $data['client_email'];
    $private_key = $data['private_key'];
    $project_id = $data['project_id'];

    // ২. অ্যাক্সেস টোকেন তৈরি করার ফাংশন
    function getAccessToken($client_email, $private_key) {
        $header = json_encode(['alg' => 'RS256', 'typ' => 'JWT']);
        $now = time();
        $payload = json_encode([
            'iss' => $client_email,
            'scope' => 'https://www.googleapis.com/auth/firebase.messaging',
            'aud' => 'https://oauth2.googleapis.com/token',
            'exp' => $now + 3600,
            'iat' => $now
        ]);

        $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
        $base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));
        
        openssl_sign($base64UrlHeader . "." . $base64UrlPayload, $signature, $private_key, OPENSSL_ALGO_SHA256);
        $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
        
        $jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;

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

    $accessToken = getAccessToken($client_email, $private_key);

    // ৩. নোটিফিকেশন মেসেজ ফরম্যাট (অ্যাপের লজিক অনুযায়ী)
    $notification = [
        'message' => [
            'topic' => 'all_users',
            'data' => [
                'title' => (string)$title,
                'message' => (string)$message,
                'actionUrl' => (string)$actionUrl,
                'image' => (string)$imageUrl
            ]
        ]
    ];

    // ৪. CURL দিয়ে FCM V1 এপিআই-তে পাঠানো
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://fcm.googleapis.com/v1/projects/$project_id/messages:send");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $accessToken,
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($notification));
    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode == 200) {
        echo "<script>alert('Notification Sent Successfully!'); window.location.href='notifications.php';</script>";
    } else {
        echo "<script>alert('Error: " . addslashes($result) . "'); window.history.back();</script>";
    }
    exit;
}
?>

<div class="control-box">
    <h4 style="color:var(--accent); margin-top:0;"><i class="fas fa-paper-plane"></i> SEND APP NOTIFICATION (V1)</h4>
    <form action="" method="POST">
        <label>Notification Title</label>
        <input type="text" name="notif_title" placeholder="মেসেজের শিরোনাম" required>
        
        <label>Description / Message</label>
        <textarea name="notif_msg" placeholder="বিস্তারিত মেসেজ..." style="width:100%; padding:10px; background:var(--input-bg); color:#fff; border:1px solid #333; border-radius:5px; margin-bottom:10px;" rows="3" required></textarea>
        
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
            <div><label>Action URL (Optional)</label><input type="url" name="action_url" placeholder="https://turkyhub.com/page"></div>
            <div><label>Banner Image URL (Optional)</label><input type="url" name="image_url" placeholder="https://site.com/image.jpg"></div>
        </div>
        
        <button class="btn" name="send_notification" style="background:var(--accent); color:#000; font-weight:bold; margin-top:15px;">
            <i class="fas fa-bell"></i> SEND NOW
        </button>
    </form>
</div>

<?php include 'footer.php'; ?>