<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

/**
 * OneSignal API Utilities
 * Handles email OTP authentication using OneSignal API
 */

require_once('config/auth_config.php');
require_once __DIR__ . '/vendor/autoload.php';
use \Firebase\JWT\JWT;
use \Firebase\JWT\Key;

// Include JWT utilities
include_once('jwt-utils.php');

// Load settings
$LOADSTRUCT = true;
$settings = require('data/settings.dat.php');

// Create database connection
$conn = new mysqli(
    $settings['mysql']['hostname'],
    $settings['mysql']['username'],
    $settings['mysql']['password'],
    $settings['mysql']['database']
);

if ($conn->connect_error) {
    die("Database connection failed");
}

date_default_timezone_set('Asia/Karachi'); // ya aapke region ka

error_log('Reached here: step 1');

/**
 * Check if user has exceeded rate limit
 * 
 * @param string $email User's email address
 * @return bool True if rate limit not exceeded, false otherwise
 */
function checkRateLimit($email) {
    global $conn, $settings;
    try {
        $email = $conn->real_escape_string($email);
        $tablePrefix = $settings['mysql']['tablePrefix'];
        
        // Check last 5 minutes attempts
        $sql = "SELECT COUNT(*) as attempt_count FROM {$tablePrefix}otp_verification 
                WHERE title = '$email' 
                AND createdDate >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)";
        
        $result = $conn->query($sql);
        if (!$result) {
            throw new Exception("Failed to check rate limit");
        }
        
        $row = $result->fetch_assoc();
        $attemptCount = $row['attempt_count'];
        
        // Check if user is locked out - TEMPORARILY DISABLED
        /*
        $sql = "SELECT COUNT(*) as lockout_count FROM {$tablePrefix}otp_verification 
                WHERE title = '$email' 
                AND content = 'LOCKED' 
                AND createdDate >= DATE_SUB(NOW(), INTERVAL 30 MINUTE)";
        
        $result = $conn->query($sql);
        if (!$result) {
            throw new Exception("Failed to check lockout");
        }
        
        $row = $result->fetch_assoc();
        $isLocked = $row['lockout_count'] > 0;
        
        if ($isLocked) {
            return [false, "Account is locked. Please try again after 30 minutes."];
        }
        
        if ($attemptCount >= 3) {
            // Lock the account
            $sql = "INSERT INTO {$tablePrefix}otp_verification (title, content, createdDate) 
                    VALUES ('$email', 'LOCKED', NOW())";
            
            if (!$conn->query($sql)) {
                throw new Exception("Failed to lock account");
            }
            
            return [false, "Too many attempts. Account locked for 30 minutes."];
        }
        */
        
        return [true, null];
    } catch (Exception $e) {
        return [false, "An error occurred while checking rate limit"];
    }
}

/**
 * Handle OneSignal API errors
 * 
 * @param mixed $response OneSignal API response
 * @return string Error message or empty string if no error
 */
function handleOneSignalError($response) {
    if (!$response) {
        return 'OneSignal service unavailable';
    }
    
    $responseData = json_decode($response, true);
    if (isset($responseData['errors'])) {
        return $responseData['errors'][0];
    }
    
    return '';
}

/**
 * Send OTP to user's email using OneSignal
 * 
 * @param string $email User's email address
 * @return array [success, message, otp]
 */
function onesignal_sendOTP($email) {
    global $conn, $settings;
    try {
        // Check rate limit
        list($allowed, $message) = checkRateLimit($email);
        if (!$allowed) {
            return [false, $message, null];
        }
        
        // Generate OTP (4 digits)
        $otp = sprintf("%04d", mt_rand(0, 9999));

        // Store OTP in database
        $email = $conn->real_escape_string($email);
        $otp = $conn->real_escape_string($otp);
        $tablePrefix = $settings['mysql']['tablePrefix'];
        
        // First mark any existing OTPs as USED
        $updateSql = "UPDATE {$tablePrefix}otp_verification 
                    SET content = 'USED' 
                    WHERE title = '$email' 
                    AND content != 'LOCKED' 
                    AND content != 'USED'";
        
        $conn->query($updateSql);
        
        // Insert new OTP
        $sql = "INSERT INTO {$tablePrefix}otp_verification (title, content, createdDate) 
                VALUES ('$email', '$otp', NOW())";
        
        if (!$conn->query($sql)) {
            throw new Exception("Failed to store OTP");
        }
        
        // Send OTP via OneSignal
        $response = sendOneSignalNotification($email, $otp);
        
        if ($response['success']) {
            return [true, "OTP sent successfully", $otp];
        } else {
            throw new Exception($response['message']);
        }
    } catch (Exception $e) {
        return [false, "Failed to send OTP", null];
    }
}

/**
 * Verify OTP for user's email
 * 
 * @param string $email User's email address
 * @param string $otp OTP to verify
 * @return array [success, message]
 */
function onesignal_verifyOTP($email, $otp) {
    global $conn, $settings;
    try {
        $email = $conn->real_escape_string($email);
        $otp = $conn->real_escape_string($otp);
        $tablePrefix = $settings['mysql']['tablePrefix'];
        
        // Get latest OTP for email
        $sql = "SELECT content, createdDate FROM {$tablePrefix}otp_verification 
                WHERE title = '$email' 
                AND content != 'LOCKED' 
                AND content != 'USED' 
                ORDER BY createdDate DESC 
                LIMIT 1";
        
        $result = $conn->query($sql);
        
        if (!$result || $result->num_rows === 0) {
            return [false, "No OTP found for this email"];
        }
        
        $row = $result->fetch_assoc();
        $storedOTP = $row['content'];
        $createdDate = strtotime($row['createdDate']);
        
        // Check if OTP is expired (10 minutes)
        // if (time() - $createdDate > 600) {
        //     return [false, "OTP has expired. Please request a new one."];
        // }
        
        // Check if OTP matches
        if ($otp !== $storedOTP) {
            // Increment failed attempts
            $sql = "INSERT INTO {$tablePrefix}otp_verification (title, content, createdDate) 
                    VALUES ('$email', 'FAILED', NOW())";
            
            $conn->query($sql);
            
            // Check if we should lock the account - TEMPORARILY DISABLED
            /*
            list($allowed, $message) = checkRateLimit($email);
            if (!$allowed) {
                return [false, $message];
            }
            */
            
            return [false, "Invalid OTP. Please try again."];
        }
        
        // Mark OTP as used
        $sql = "UPDATE {$tablePrefix}otp_verification 
                SET content = 'USED' 
                WHERE title = '$email' 
                AND content = '$otp'";
        
        if (!$conn->query($sql)) {
            return [false, "Failed to verify OTP"];
        }
        
        return [true, "OTP verified successfully"];
    } catch (Exception $e) {
        return [false, "An error occurred while verifying OTP"];
    }
}

/**
 * Generate JWT token for authenticated user
 * 
 * @param array $user User data
 * @return string JWT token
 */
function onesignal_generateToken($user) {
    $payload = [
        'iss' => 'urbanhalal',
        'sub' => $user['num'],
        'email' => $user['email'],
        'username' => $user['username']
    ];
    
    return jwt_generateToken($payload);
}

/**
 * Validate JWT token
 * 
 * @param string $token JWT token
 * @return array [success, user_data]
 */
function onesignal_validateToken($token) {
    return jwt_validateToken($token);
}

/**
 * Send notification via OneSignal API
 * 
 * @param string $email User's email address
 * @param string $otp OTP to send
 * @return array [success, message]
 */
function sendOneSignalNotification($email, $otp) {
    try {
        // Prepare OneSignal notification
        $notification = [
            'app_id' => $GLOBALS['ONESIGNAL_APP_ID'],
            'include_email_tokens' => [$email],
            'email_subject' => 'Your OTP Code',
            'email_body' => "Your OTP code is: $otp\n\nThis code will expire in 10 minutes.\n\nDo not share this code with anyone.",
            'email_from_name' => 'CaterBox'
        ];
        
        // 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',
            'Authorization: Basic ' . $GLOBALS['ONESIGNAL_REST_API_KEY']
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($notification));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        
        if (curl_errno($ch)) {
            curl_close($ch);
            throw new Exception("Failed to connect to OneSignal service");
        }
        
        curl_close($ch);
        
        if ($httpCode === 200) {
            $responseData = json_decode($response, true);
            if (json_last_error() === JSON_ERROR_NONE) {
                return ['success' => true, 'message' => 'OTP sent successfully'];
            } else {
                throw new Exception("Invalid response from OneSignal service");
            }
        } else {
            $errorMessage = handleOneSignalError($response);
            throw new Exception($errorMessage ?: "Failed to send OTP");
        }
    } catch (Exception $e) {
        return ['success' => false, 'message' => $e->getMessage()];
    }
}

/**
 * Send Group Order Invite via OneSignal Email
 * @param string $email
 * @param string $link
 * @param string $message
 * @return array [success, message]
 */
function sendGroupOrderInvite($email, $link, $message) {
    // Make sure OneSignal config is set
    if (!isset($GLOBALS['ONESIGNAL_APP_ID']) || !isset($GLOBALS['ONESIGNAL_REST_API_KEY'])) {
        return [false, 'OneSignal config missing', null];
    }
    $notification = [
        'app_id' => $GLOBALS['ONESIGNAL_APP_ID'],
        'include_email_tokens' => [$email],
        'email_subject' => 'Group Order Invitation',
        'email_body' => $message . "\n\nJoin your group order: $link",
        'email_from_name' => 'Cater4Love'
    ];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://onesignal.com/api/v1/notifications');
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Basic ' . $GLOBALS['ONESIGNAL_REST_API_KEY']
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($notification));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($httpCode === 200) {
        return [true, 'Invite sent successfully', null];
    } else {
        return [false, 'Failed to send invite', null];
    }
}

/**
 * Check if user is locked out
 * 
 * @param string $email User's email address
 * @return array ['locked' => bool, 'until' => string|null]
 */
function isUserLocked($email) {
    global $conn, $settings;
    $email = $conn->real_escape_string($email);
    $tablePrefix = $settings['mysql']['tablePrefix'];
    
    $sql = "SELECT * FROM {$tablePrefix}members WHERE email = '$email' AND lockout_until > NOW()";
    $result = $conn->query($sql);
    
    if ($result && $result->num_rows > 0) {
        $user = $result->fetch_assoc();
        return [
            'locked' => true,
            'until' => $user['lockout_until']
        ];
    }
    
    return ['locked' => false];
}

/**
 * Send OTP to restaurant owner's email using OneSignal
 * 
 * @param string $email Restaurant owner's email address
 * @return array [success, message, otp]
 */
function onesignal_sendRestaurantOTP($email) {
    global $conn, $settings;
    try {
        // Check rate limit
        list($allowed, $message) = checkRateLimit($email);
        if (!$allowed) {
            return [false, $message, null];
        }
        
        // Generate OTP (4 digits)
        $otp = sprintf("%04d", mt_rand(0, 9999));

        // Store OTP in database
        $email = $conn->real_escape_string($email);
        $otp = $conn->real_escape_string($otp);
        $tablePrefix = $settings['mysql']['tablePrefix'];
        
        // First mark any existing OTPs as USED
        $updateSql = "UPDATE {$tablePrefix}otp_verification 
                    SET content = 'USED' 
                    WHERE title = '$email' 
                    AND content != 'LOCKED' 
                    AND content != 'USED'";
        
        $conn->query($updateSql);
        
        // Insert new OTP
        $sql = "INSERT INTO {$tablePrefix}otp_verification (title, content, createdDate) 
                VALUES ('$email', '$otp', NOW())";
        
        if (!$conn->query($sql)) {
            throw new Exception("Failed to store OTP");
        }
        
        // Send OTP via OneSignal
        $response = sendOneSignalRestaurantNotification($email, $otp);
        
        if ($response['success']) {
            return [true, "OTP sent successfully to restaurant owner", $otp];
        } else {
            throw new Exception($response['message']);
        }
    } catch (Exception $e) {
        return [false, "Failed to send OTP to restaurant owner", null];
    }
}

/**
 * Verify OTP for restaurant owner's email
 * 
 * @param string $email Restaurant owner's email address
 * @param string $otp OTP to verify
 * @return array [success, message]
 */
function onesignal_verifyRestaurantOTP($email, $otp) {
    global $conn, $settings;
    try {
        $email = $conn->real_escape_string($email);
        $otp = $conn->real_escape_string($otp);
        $tablePrefix = $settings['mysql']['tablePrefix'];
        
        // Get latest OTP for email
        $sql = "SELECT content, createdDate FROM {$tablePrefix}otp_verification 
                WHERE title = '$email' 
                AND content != 'LOCKED' 
                AND content != 'USED' 
                ORDER BY createdDate DESC 
                LIMIT 1";
        
        $result = $conn->query($sql);
        
        if (!$result || $result->num_rows === 0) {
            return [false, "No OTP found for this email"];
        }
        
        $row = $result->fetch_assoc();
        $storedOTP = $row['content'];
        $createdDate = strtotime($row['createdDate']);
        
        // Check if OTP is expired (10 minutes)
        // if (time() - $createdDate > 600) {
        //     return [false, "OTP has expired. Please request a new one."];
        // }
        
        // Check if OTP matches
        if ($otp !== $storedOTP) {
            // Increment failed attempts
            $sql = "INSERT INTO {$tablePrefix}otp_verification (title, content, createdDate) 
                    VALUES ('$email', 'FAILED', NOW())";
            
            $conn->query($sql);
            
            // Check if we should lock the account
            // list($allowed, $message) = checkRateLimit($email);
            // if (!$allowed) {
            //     return [false, $message];
            // }
            
            return [false, "Invalid OTP. Please try again."];
        }
        
        // Mark OTP as used
        $sql = "UPDATE {$tablePrefix}otp_verification 
                SET content = 'USED' 
                WHERE title = '$email' 
                AND content = '$otp'";
        
        if (!$conn->query($sql)) {
            return [false, "Failed to verify OTP"];
        }
        
        return [true, "Restaurant owner OTP verified successfully"];
    } catch (Exception $e) {
        return [false, "An error occurred while verifying restaurant owner OTP"];
    }
}

/**
 * Generate JWT token for restaurant owner (1 year expiry)
 * 
 * @param array $restaurant Restaurant data
 * @return string JWT token
 */
function onesignal_generateRestaurantToken($restaurant) {
    $payload = [
        'iss' => 'urbanhalal',
        'sub' => $restaurant['num'],
        'email' => $restaurant['email'],
        'restaurant_name' => $restaurant['name'],
        'type' => 'restaurant_owner',
        'exp' => time() + (365 * 24 * 60 * 60) // 1 year expiry
    ];
    
    return JWT::encode($payload, $GLOBALS['JWT_SECRET'], 'HS256');
}

/**
 * Send notification to restaurant owner via OneSignal API
 * 
 * @param string $email Restaurant owner's email address
 * @param string $otp OTP to send
 * @return array [success, message]
 */
function sendOneSignalRestaurantNotification($email, $otp) {
    try {
        // Prepare OneSignal notification for restaurant owner
        $notification = [
            'app_id' => $GLOBALS['ONESIGNAL_APP_ID'],
            'include_email_tokens' => [$email],
            'email_subject' => 'Restaurant Owner Login - OTP Code',
            'email_body' => "Your OTP code for restaurant owner login is: $otp\n\nThis code will expire in 10 minutes.\n\nDo not share this code with anyone.\n\nBest regards,\CaterBox Team",
            'email_from_name' => 'CaterBox - Restaurant Portal'
        ];
        
        // 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',
            'Authorization: Basic ' . $GLOBALS['ONESIGNAL_REST_API_KEY']
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($notification));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        
        if (curl_errno($ch)) {
            curl_close($ch);
            throw new Exception("Failed to connect to OneSignal service");
        }
        
        curl_close($ch);
        
        if ($httpCode === 200) {
            $responseData = json_decode($response, true);
            if (json_last_error() === JSON_ERROR_NONE) {
                return ['success' => true, 'message' => 'OTP sent successfully to restaurant owner'];
            } else {
                throw new Exception("Invalid response from OneSignal service");
            }
        } else {
            $errorMessage = handleOneSignalError($response);
            throw new Exception($errorMessage ?: "Failed to send OTP to restaurant owner");
        }
    } catch (Exception $e) {
        return ['success' => false, 'message' => $e->getMessage()];
    }
}



/**
 * Send Order Confirmation Email to Restaurant Owner
 * @param int $orderNum Order number
 * @param array $orderData Order details
 * @param array $restaurant Restaurant data
 * @return array [success, message]
 */
function sendOrderConfirmationToRestaurant($orderNum, $orderData, $restaurant) {
    try {
        // Make sure OneSignal config is set
        if (!isset($GLOBALS['ONESIGNAL_APP_ID']) || !isset($GLOBALS['ONESIGNAL_REST_API_KEY'])) {
            return [false, 'OneSignal config missing'];
        }

        // Get order details
        $orderNumber = $orderData['order_number'] ?? $orderNum;
        $orderDate = date('Y-m-d H:i:s');
        $totalAmount = $orderData['total_amount'] ?? 0;
        $customerName = $orderData['customer_name'] ?? 'Customer';
        $customerPhone = $orderData['customer_phone'] ?? 'N/A';
        $customerAddress = $orderData['customer_address'] ?? 'N/A';
        
        // Get order type information
        $orderDeliveryType = $orderData['order_delivery_type'] ?? 'Standard';
        $paymentType = $orderData['payment_type'] ?? 'N/A';
        $orderStatus = $orderData['order_status'] ?? 'Pending';
        $orderStatusText = $orderData['order_status_text'] ?? '';
        
        // Build order items list
        $orderItems = '';
        if (isset($orderData['order_items']) && is_array($orderData['order_items'])) {
            foreach ($orderData['order_items'] as $item) {
                $itemName = $item['name'] ?? 'Unknown Item';
                $itemQty = $item['quantity'] ?? 1;
                $itemPrice = $item['price'] ?? 0;
                $orderItems .= "• {$itemName} x {$itemQty} - $" . number_format($itemPrice, 2) . "\n";
            }
        }

        // Prepare email content for restaurant
        $emailSubject = "New Order #{$orderNumber} - CaterBox";
        $emailBody = "🎉 NEW ORDER RECEIVED! 🎉

Order Details:
Order Number: #{$orderNumber}
Order Date: {$orderDate}
Total Amount: $" . number_format($totalAmount, 2) . "

Order Type Information:
Delivery Type: {$orderDeliveryType}
Payment Type: {$paymentType}
Order Status: {$orderStatus}" . ($orderStatusText ? "\nStatus Details: {$orderStatusText}" : "") . "

Customer Information:
Name: {$customerName}
Phone: {$customerPhone}
Address: {$customerAddress}

Order Items:
{$orderItems}

Please prepare this order and update the status in your dashboard.

Best regards,
CaterBox Team";

        // Send notification via OneSignal API
        $notification = [
            'app_id' => $GLOBALS['ONESIGNAL_APP_ID'],
            'include_email_tokens' => [$restaurant['email']],
            'email_subject' => $emailSubject,
            'email_body' => $emailBody,
            'email_from_name' => 'CaterBox'
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://onesignal.com/api/v1/notifications');
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Authorization: Basic ' . $GLOBALS['ONESIGNAL_REST_API_KEY']
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($notification));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        
        if (curl_errno($ch)) {
            curl_close($ch);
            throw new Exception("Failed to connect to OneSignal service");
        }
        
        curl_close($ch);
        
        if ($httpCode === 200) {
            return [true, 'Order confirmation sent to restaurant successfully'];
        } else {
            $errorMessage = handleOneSignalError($response);
            throw new Exception($errorMessage ?: "Failed to send order confirmation to restaurant");
        }
    } catch (Exception $e) {
        return [false, 'Failed to send order confirmation to restaurant: ' . $e->getMessage()];
    }
}

/**
 * Send Order Confirmation Email to Customer
 * @param int $orderNum Order number
 * @param array $orderData Order details
 * @param array $user User data
 * @param array $restaurant Restaurant data
 * @return array [success, message]
 */
function sendOrderConfirmationToCustomer($orderNum, $orderData, $user, $restaurant) {
    try {
        // Make sure OneSignal config is set
        if (!isset($GLOBALS['ONESIGNAL_APP_ID']) || !isset($GLOBALS['ONESIGNAL_REST_API_KEY'])) {
            return [false, 'OneSignal config missing'];
        }

        // Get order details
        $orderNumber = $orderData['order_number'] ?? $orderNum;
        $orderDate = date('Y-m-d H:i:s');
        $totalAmount = $orderData['total_amount'] ?? 0;
        $restaurantName = $restaurant['name'] ?? 'Restaurant';
        $restaurantAddress = $restaurant['address'] ?? 'N/A';
        $estimatedDelivery = $orderData['estimated_delivery'] ?? '30-45 minutes';
        
        // Get order type information
        $orderDeliveryType = $orderData['order_delivery_type'] ?? 'Standard';
        $paymentType = $orderData['payment_type'] ?? 'N/A';
        $orderStatus = $orderData['order_status'] ?? 'Pending';
        $orderStatusText = $orderData['order_status_text'] ?? '';
        
        // Build order items list
        $orderItems = '';
        if (isset($orderData['order_items']) && is_array($orderData['order_items'])) {
            foreach ($orderData['order_items'] as $item) {
                $itemName = $item['name'] ?? 'Unknown Item';
                $itemQty = $item['quantity'] ?? 1;
                $itemPrice = $item['price'] ?? 0;
                $orderItems .= "• {$itemName} x {$itemQty} - $" . number_format($itemPrice, 2) . "\n";
            }
        }

        // Prepare email content for customer
        $emailSubject = "Order Confirmation #{$orderNumber} - CaterBox";
        $emailBody = "🎉 ORDER CONFIRMED! 🎉

Thank you for your order!

Order Details:
Order Number: #{$orderNumber}
Order Date: {$orderDate}
Total Amount: $" . number_format($totalAmount, 2) . "
Estimated Delivery: {$estimatedDelivery}

Order Type Information:
Delivery Type: {$orderDeliveryType}
Payment Type: {$paymentType}
Order Status: {$orderStatus}" . ($orderStatusText ? "\nStatus Details: {$orderStatusText}" : "") . "

Restaurant: {$restaurantName}
Address: {$restaurantAddress}

Your Order:
{$orderItems}

We'll notify you when your order is ready for pickup or delivery.

Track your order status in the CaterBox app.

Thank you for choosing CaterBox!

Best regards,
CaterBox Team";

        // Send notification via OneSignal API
        $notification = [
            'app_id' => $GLOBALS['ONESIGNAL_APP_ID'],
            'include_email_tokens' => [$user['email']],
            'email_subject' => $emailSubject,
            'email_body' => $emailBody,
            'email_from_name' => 'CaterBox'
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://onesignal.com/api/v1/notifications');
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Authorization: Basic ' . $GLOBALS['ONESIGNAL_REST_API_KEY']
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($notification));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        
        if (curl_errno($ch)) {
            curl_close($ch);
            throw new Exception("Failed to connect to OneSignal service");
        }
        
        curl_close($ch);
        
        if ($httpCode === 200) {
            return [true, 'Order confirmation sent to customer successfully'];
        } else {
            $errorMessage = handleOneSignalError($response);
            throw new Exception($errorMessage ?: "Failed to send order confirmation to customer");
        }
    } catch (Exception $e) {
        return [false, 'Failed to send order confirmation to customer: ' . $e->getMessage()];
    }
}

/**
 * Get Restaurant Information from Order Data
 * This function tries multiple ways to find restaurant information
 * @param array $orderData Order data
 * @param object $conn Database connection
 * @param array $settings Database settings
 * @return array [restaurant_data, restaurant_id] or [null, null] if not found
 */
function getRestaurantFromOrder($orderData, $conn, $settings) {
    try {
        $restaurantId = null;
        $restaurant = null;
        
        // Method 1: Direct restaurant_id in order data
        if (isset($orderData['restaurant_id']) && $orderData['restaurant_id']) {
            $restaurantId = $orderData['restaurant_id'];
        }
        
        // Method 2: Restaurant ID from first order item
        if (!$restaurantId && isset($orderData['order_items']) && is_array($orderData['order_items'])) {
            foreach ($orderData['order_items'] as $item) {
                if (isset($item['restaurant_id']) && $item['restaurant_id']) {
                    $restaurantId = $item['restaurant_id'];
                    break;
                }
            }
        }
        
        // Method 3: Restaurant ID from menu items
        if (!$restaurantId && isset($orderData['order_items']) && is_array($orderData['order_items'])) {
            foreach ($orderData['order_items'] as $item) {
                if (isset($item['productsNum'])) {
                    $tablePrefix = $settings['mysql']['tablePrefix'];
                    $menuSql = "SELECT * FROM {$tablePrefix}menu WHERE num = ?";
                    $stmt = $conn->prepare($menuSql);
                    if ($stmt) {
                        $stmt->bind_param("i", $item['productsNum']);
                        $stmt->execute();
                        $result = $stmt->get_result();
                        if ($result && $result->num_rows > 0) {
                            $menuItem = $result->fetch_assoc();
                            if (isset($menuItem['listingsNum']) && $menuItem['listingsNum']) {
                                $restaurantId = $menuItem['listingsNum'];
                                break;
                            }
                        }
                        $stmt->close();
                    }
                }
            }
        }
        
        // Method 4: Try to find restaurant from order table
        if (!$restaurantId && isset($orderData['order_num'])) {
            $tablePrefix = $settings['mysql']['tablePrefix'];
            $orderSql = "SELECT listingsNum FROM {$tablePrefix}orders WHERE num = ?";
            $stmt = $conn->prepare($orderSql);
            if ($stmt) {
                $stmt->bind_param("i", $orderData['order_num']);
                $stmt->execute();
                $result = $stmt->get_result();
                if ($result && $result->num_rows > 0) {
                    $orderRow = $result->fetch_assoc();
                    if (isset($orderRow['listingsNum']) && $orderRow['listingsNum']) {
                        $restaurantId = $orderRow['listingsNum'];
                    }
                }
                $stmt->close();
            }
        }
        
        // If we found a restaurant ID, get the restaurant details from cmsb_listings table
        if ($restaurantId) {
            $tablePrefix = $settings['mysql']['tablePrefix'];
            $restaurantSql = "SELECT * FROM {$tablePrefix}listings WHERE num = ?";
            $stmt = $conn->prepare($restaurantSql);
            if ($stmt) {
                $stmt->bind_param("i", $restaurantId);
                $stmt->execute();
                $result = $stmt->get_result();
                if ($result && $result->num_rows > 0) {
                    $restaurant = $result->fetch_assoc();
                    
                    // Map the fields to match expected structure
                    $restaurant['name'] = $restaurant['name'] ?? 'Restaurant';
                    $restaurant['email'] = $restaurant['email'] ?? '';
                    $restaurant['address'] = trim(
                        ($restaurant['address_1'] ?? '') . ', ' . 
                        ($restaurant['city'] ?? '') . ', ' . 
                        ($restaurant['state'] ?? '') . ' ' . 
                        ($restaurant['zip'] ?? ''), 
                        ', '
                    );
                    $restaurant['phone'] = $restaurant['phone'] ?? '';
                }
                $stmt->close();
            }
        }
        
        return [$restaurant, $restaurantId];
        
    } catch (Exception $e) {
        error_log("Error getting restaurant from order: " . $e->getMessage());
        return [null, null];
    }
}

/**
 * Send Order Confirmation Emails (Main Function)
 * This function should be called after a successful order placement
 * @param int $orderNum Order number
 * @param array $orderData Order details
 * @param array $user User data
 * @return array [success, message]
 */
function sendOrderConfirmationEmails($orderNum, $orderData, $user) {
    try {
        global $conn, $settings;
        
        // Check if database connection exists
        if (!$conn) {
            return [false, 'Database connection not available'];
        }
        
        // Get restaurant information using the helper function
        list($restaurant, $restaurantId) = getRestaurantFromOrder($orderData, $conn, $settings);
        
        if (!$restaurant) {
            return [false, 'Restaurant information not found for order'];
        }
        
        // Send email to restaurant
        $restaurantResult = sendOrderConfirmationToRestaurant($orderNum, $orderData, $restaurant);
        
        // Send email to customer
        $customerResult = sendOrderConfirmationToCustomer($orderNum, $orderData, $user, $restaurant);
        
        if ($restaurantResult[0] && $customerResult[0]) {
            return [true, 'Order confirmation emails sent successfully to both restaurant and customer'];
        } elseif ($restaurantResult[0]) {
            return [true, 'Order confirmation sent to restaurant only. Customer email failed: ' . $customerResult[1]];
        } elseif ($customerResult[0]) {
            return [true, 'Order confirmation sent to customer only. Restaurant email failed: ' . $restaurantResult[1]];
        } else {
            return [false, 'Failed to send order confirmation emails. Restaurant: ' . $restaurantResult[1] . ', Customer: ' . $customerResult[1]];
        }
        
    } catch (Exception $e) {
        return [false, 'Exception occurred while sending order confirmation emails: ' . $e->getMessage()];
    }
}

