<?php

require './core.php';

/**
 * Send push notification to store followers
 * This function is called when a new coupon is added or updated
 */
function sendStoreNotification($store_id, $coupon_id, $notification_type = 'new_coupon') {
    global $connect;
    
    // Get push notification settings
    $settings_query = $connect->query("SELECT * FROM push_notification_settings WHERE id = 1");
    $push_settings = $settings_query->fetch(PDO::FETCH_ASSOC);
    
    // Check if notifications are enabled
    if (!$push_settings || !$push_settings['notification_enabled'] || !$push_settings['new_coupon_notification']) {
        return false;
    }
    
    if (empty($push_settings['onesignal_app_id']) || empty($push_settings['onesignal_api_key'])) {
        return false;
    }
    
    // Get store details
    $store_query = $connect->prepare("SELECT store_title, store_image FROM stores WHERE store_id = :store_id");
    $store_query->execute([':store_id' => $store_id]);
    $store = $store_query->fetch(PDO::FETCH_ASSOC);
    
    if (!$store) {
        return false;
    }
    
    // Get coupon details
    $coupon_query = $connect->prepare("SELECT coupon_title, coupon_code, coupon_slug FROM coupons WHERE coupon_id = :coupon_id");
    $coupon_query->execute([':coupon_id' => $coupon_id]);
    $coupon = $coupon_query->fetch(PDO::FETCH_ASSOC);
    
    if (!$coupon) {
        return false;
    }
    
    // Get all followers of this store
    $followers_query = $connect->prepare("SELECT player_id FROM store_followers WHERE store_id = :store_id");
    $followers_query->execute([':store_id' => $store_id]);
    $followers = $followers_query->fetchAll(PDO::FETCH_COLUMN);
    
    if (empty($followers)) {
        return false; // No followers to notify
    }
    
    // Prepare notification content
    $title = "🎉 New Deal at " . $store['store_title'];
    $message = $coupon['coupon_title'];
    if (!empty($coupon['coupon_code'])) {
        $message .= " - Use code: " . $coupon['coupon_code'];
    }
    
    $url = SITE_URL . '/coupon/' . $coupon['coupon_slug'];
    $icon = SITE_URL . '/images/' . $store['store_image'];
    
    // Prepare OneSignal API request
    $fields = [
        'app_id' => $push_settings['onesignal_app_id'],
        'include_player_ids' => $followers,
        'headings' => ['en' => $title],
        'contents' => ['en' => $message],
        'url' => $url,
        'chrome_web_icon' => $icon,
        'firefox_icon' => $icon,
        'chrome_web_badge' => $icon,
        'data' => [
            'store_id' => $store_id,
            'coupon_id' => $coupon_id,
            'type' => 'new_coupon'
        ],
        'tags' => [
            ['key' => 'store_' . $store_id, 'relation' => '=', 'value' => 'true']
        ]
    ];
    
    // Send notification via OneSignal API
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://onesignal.com/api/v1/notifications');
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json; charset=utf-8',
        'Authorization: Basic ' . $push_settings['onesignal_api_key']
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    $result = json_decode($response, true);
    
    // Log notification
    $sent_to = count($followers);
    $successful = $result['recipients'] ?? 0;
    $failed = $sent_to - $successful;
    
    $log_insert = $connect->prepare("
        INSERT INTO notification_logs (store_id, coupon_id, notification_type, title, message, sent_to, successful, failed)
        VALUES (:store_id, :coupon_id, :type, :title, :message, :sent_to, :successful, :failed)
    ");
    
    $log_insert->execute([
        ':store_id' => $store_id,
        ':coupon_id' => $coupon_id,
        ':type' => $notification_type,
        ':title' => $title,
        ':message' => $message,
        ':sent_to' => $sent_to,
        ':successful' => $successful,
        ':failed' => $failed
    ]);
    
    return [
        'success' => $http_code === 200,
        'sent_to' => $sent_to,
        'successful' => $successful,
        'failed' => $failed,
        'response' => $result
    ];
}

/**
 * Send welcome notification to new subscriber
 */
function sendWelcomeNotification($player_id) {
    global $connect;
    
    // Get push notification settings
    $settings_query = $connect->query("SELECT * FROM push_notification_settings WHERE id = 1");
    $push_settings = $settings_query->fetch(PDO::FETCH_ASSOC);
    
    if (!$push_settings || !$push_settings['notification_enabled'] || !$push_settings['welcome_notification']) {
        return false;
    }
    
    if (empty($push_settings['onesignal_app_id']) || empty($push_settings['onesignal_api_key'])) {
        return false;
    }
    
    $title = "Welcome to Alonedeals! 🎉";
    $message = "Thanks for subscribing! You'll now receive notifications about new deals from your favorite stores.";
    $url = SITE_URL;
    
    $fields = [
        'app_id' => $push_settings['onesignal_app_id'],
        'include_player_ids' => [$player_id],
        'headings' => ['en' => $title],
        'contents' => ['en' => $message],
        'url' => $url
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://onesignal.com/api/v1/notifications');
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json; charset=utf-8',
        'Authorization: Basic ' . $push_settings['onesignal_api_key']
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    return json_decode($response, true);
}

// If called directly (for testing)
if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
    // Example: Send test notification
    if (isset($_GET['test']) && isset($_GET['store_id']) && isset($_GET['coupon_id'])) {
        $result = sendStoreNotification($_GET['store_id'], $_GET['coupon_id']);
        header('Content-Type: application/json');
        echo json_encode($result);
    } else {
        echo "Push notification sender ready. Use sendStoreNotification() function.";
    }
}

?>
