<?php
// INCLUDE YOUR FCM FILE
include_once 'db_connect.php';

require_once __DIR__ . '/vendor/autoload.php';
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\HttpHandler\HttpHandlerFactory;

class FCMNotifier {
    private $serviceAccountKeyFile;
    private $scope = "https://www.googleapis.com/auth/firebase.messaging";

    public function __construct() {
        $this->serviceAccountKeyFile = __DIR__ . '/auth/service_key.json';
    }

    private function getAccessToken() {
        $credentials = new ServiceAccountCredentials($this->scope, $this->serviceAccountKeyFile);
        $token = $credentials->fetchAuthToken(HttpHandlerFactory::build());
        return $token['access_token'];
    }
    
    public function handlePostRequest() {
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            $uid = $_POST['uid'] ?? '';
            $android_id = $_POST['android_id'] ?? '';
            $title = $_POST['title'] ?? '';
            $body = $_POST['body'] ?? '';

            if ($uid && $android_id && $title && $body) {
                $this->processRequest($uid, $android_id, $title, $body);
            } else {
                $this->sendResponse(['error' => 'Missing required parameters']);
            }
        } else {
            $this->sendResponse(['error' => 'Invalid request method']);
        }
    }

    private function processRequest($uid, $android_id, $title, $body) {
        global $con; // Use the global connection object
        $query = mysqli_query($con, "SELECT * FROM device_reg WHERE uid='$uid' AND android_id='$android_id'");
        if (mysqli_num_rows($query) >= 1) {
            $row = mysqli_fetch_assoc($query);
            $regId = $row['token'];

            $this->sendGCM($title, $body, $regId);

            $responseMessage = $this->getResponseMessage($title);
            $response = ["error" => "false", "message" => $responseMessage];
        } else {
            $response = ["error" => "false", "message" => "Error sending request to a device"];
        }
        
        $this->sendResponse($response);
    }

    private function sendGCM($title, $message, $token) {
        $url = 'https://fcm.googleapis.com/v1/projects/your-project-id/messages:send'; // Update with your project ID
        $accessToken = $this->getAccessToken();
        $headers = [
            'Authorization: Bearer ' . $accessToken,
            'Content-Type: application/json'
        ];

        require_once('Notifications.php');
        $notification = new Notifications();
        $notification->setTitle($title);
        $notification->setMessage($message);
        $requestData = $notification->getNotification();

        $fields = [
            'message' => [
                'token' => $token,
                'data' => $requestData,
            ]
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // Ensure the SSL certificate is valid
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        $result = curl_exec($ch);
        if ($result === FALSE) {
            $this->sendResponse(['error' => 'Curl failed: ' . curl_error($ch)]);
        }
        curl_close($ch);
    }

    private function getResponseMessage($title) {
        switch ($title) {
            case 'ringSilent':
            case 'ringPlay':
                return 'The device you requested will ring soon!';
            case 'flashLight':
                return 'Turn on FlashLight soon!';
            case 'lockPhone':
                return 'The device you requested will lock soon!';
            case 'eraseData':
                return 'The device you requested to delete data will erase data soon!';
            default:
                return 'Unknown request';
        }
    }

    private function sendResponse($response) {
        header('Content-Type: application/json');
        echo json_encode($response);
        exit();
    }
}

$notifier = new FCMNotifier();
$notifier->handlePostRequest();
mysqli_close($con);
?>
