<?php
/**
 * Tom's Java Jive - Test Notification API
 */

header('Content-Type: application/json');

require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/email.php';
require_once __DIR__ . '/../includes/sms.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(['error' => 'Method not allowed'], 405);
}

$input = json_decode(file_get_contents('php://input'), true);
$type = $input['type'] ?? '';
$recipient = $input['recipient'] ?? '';

if (empty($recipient)) {
    jsonResponse(['error' => 'Recipient is required'], 400);
}

switch ($type) {
    case 'email':
        if (!filter_var($recipient, FILTER_VALIDATE_EMAIL)) {
            jsonResponse(['error' => 'Invalid email address'], 400);
        }
        
        $result = emailService()->send(
            $recipient,
            "Test Email from Tom's Java Jive",
            "<div style='font-family: Arial, sans-serif; max-width: 500px; margin: 0 auto; padding: 20px;'>
                <h2 style='color: #FF5E1A;'>Test Email</h2>
                <p>This is a test email from your Tom's Java Jive store.</p>
                <p>If you received this, your SendGrid integration is working correctly!</p>
                <p style='color: #666; font-size: 0.9em; margin-top: 30px;'>
                    Sent at: " . date('Y-m-d H:i:s') . "
                </p>
            </div>"
        );
        
        if ($result['success']) {
            jsonResponse(['success' => true, 'message' => 'Test email sent to ' . $recipient]);
        } else {
            jsonResponse(['success' => false, 'error' => $result['error'] ?? 'Failed to send email']);
        }
        break;
        
    case 'sms':
        $result = sendSMS()->send(
            $recipient,
            "Tom's Java Jive: This is a test message. If you received this, your Twilio integration is working! Sent at " . date('g:i A')
        );
        
        if ($result['success']) {
            jsonResponse(['success' => true, 'message' => 'Test SMS sent to ' . $recipient]);
        } else {
            jsonResponse(['success' => false, 'error' => $result['error'] ?? 'Failed to send SMS']);
        }
        break;
        
    default:
        jsonResponse(['error' => 'Invalid notification type'], 400);
}
