<?php
/**
 * Send Order Emails - TEMPLATE VERSION
 * File: send-order-emails.php (ROOT)
 * Uses templates/email/*.php via Mailer::getTemplate()
 */

require_once 'app/Core/init.php';

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

$order_id = $_GET['order_id'] ?? 0;

if (!$order_id) {
    echo json_encode(['success' => false, 'message' => 'No order ID provided']);
    exit;
}

try {
    $db = Database::getInstance();

    $orderSql = "SELECT o.*, 
                 i.title as item_title, 
                 i.price_per_day as daily_rate,
                 CONCAT(c.first_name, ' ', c.last_name) as customer_name,
                 c.phone as customer_phone, 
                 u_c.email as customer_email,
                 v.business_name as vendor_name, 
                 v.phone as vendor_phone,
                 v.city as vendor_city,
                 v.state as vendor_state,
                 u_v.email as vendor_email,
                 op.transaction_reference, 
                 op.payment_gateway
                 FROM orders o
                 JOIN items i ON o.item_id = i.id
                 JOIN customers c ON o.customer_id = c.id
                 JOIN users u_c ON c.user_id = u_c.id
                 JOIN vendors v ON o.vendor_id = v.id
                 JOIN users u_v ON v.user_id = u_v.id
                 LEFT JOIN online_payments op ON o.id = op.order_id
                 WHERE o.id = ?";

    $orderData = $db->fetch($orderSql, [$order_id]);

    if (!$orderData) {
        echo json_encode(['success' => false, 'message' => 'Order not found']);
        exit;
    }

    $mailer      = new Mailer();
    $results     = [];
    $all_success = true;

    // 1. CUSTOMER - templates/email/order-confirmation.php
    try {
        $sent = $mailer->sendOrderConfirmation($orderData);
        $results['customer'] = ['status' => $sent ? 'sent' : 'failed', 'to' => $orderData['customer_email']];
        if (!$sent) $all_success = false;
    } catch (Exception $e) {
        $results['customer'] = ['status' => 'error', 'message' => $e->getMessage(), 'to' => $orderData['customer_email']];
        $all_success = false;
        error_log("Customer email error: " . $e->getMessage());
    }

    // 2. VENDOR - templates/email/order-notification-vendor.php
    try {
        $sent = $mailer->sendVendorOrderNotification($orderData);
        $results['vendor'] = ['status' => $sent ? 'sent' : 'failed', 'to' => $orderData['vendor_email']];
        if (!$sent) $all_success = false;
    } catch (Exception $e) {
        $results['vendor'] = ['status' => 'error', 'message' => $e->getMessage(), 'to' => $orderData['vendor_email'] ?? 'unknown'];
        $all_success = false;
        error_log("Vendor email error: " . $e->getMessage());
    }

    // 3. ADMIN - templates/email/order-notification-admin.php
    try {
        $sent = $mailer->sendAdminOrderNotification($orderData);
        $results['admin'] = ['status' => $sent ? 'sent' : 'failed', 'to' => defined('ADMIN_EMAIL') ? ADMIN_EMAIL : 'admin@rentidium.ng'];
        if (!$sent) $all_success = false;
    } catch (Exception $e) {
        $results['admin'] = ['status' => 'error', 'message' => $e->getMessage(), 'to' => 'admin'];
        $all_success = false;
        error_log("Admin email error: " . $e->getMessage());
    }

    error_log("Order emails sent for #{$orderData['order_number']}: " . json_encode($results));

    echo json_encode([
        'success'      => $all_success,
        'message'      => $all_success ? 'All emails sent successfully' : 'Some emails failed',
        'order_number' => $orderData['order_number'],
        'order_id'     => $order_id,
        'results'      => $results,
        'timestamp'    => date('Y-m-d H:i:s')
    ]);

} catch (Exception $e) {
    error_log("Send order emails critical error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}