<?php
session_start();
header('Content-Type: application/json');

// Check if user is admin or staff
if (!isset($_SESSION['user_role']) || !in_array($_SESSION['user_role'], ['admin', 'staff'], true)) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

require_once __DIR__ . '/../config/db.php';

if ($connection->connect_error) {
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit;
}

$order_id = intval($_POST['order_id'] ?? 0);
$status = trim($_POST['status'] ?? '');

if ($order_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid order ID']);
    exit;
}

$allowed_statuses = ['pending', 'processing', 'shipped', 'delivered', 'cancelled'];
if (!in_array($status, $allowed_statuses)) {
    echo json_encode(['success' => false, 'message' => 'Invalid status value']);
    exit;
}

// Get order details including customer email
$order_stmt = $connection->prepare("
    SELECT o.id, u.email, u.name FROM orders o 
    JOIN users u ON o.user_id = u.id 
    WHERE o.id = ?
");
$order_stmt->bind_param("i", $order_id);
$order_stmt->execute();
$order_result = $order_stmt->get_result();
$order = $order_result->fetch_assoc();

// Update order status
$stmt = $connection->prepare("UPDATE orders SET status = ? WHERE id = ?");
$stmt->bind_param("si", $status, $order_id);

if ($stmt->execute()) {
    // Return success immediately (email in background)
    echo json_encode(['success' => true, 'message' => 'Order status updated successfully']);
    
    // Send delivery email (non-blocking)
    if ($status === 'delivered' && $order) {
        // Use ignore_user_abort to send email after response
        ignore_user_abort(true);
        sendDeliveryEmail($order, $connection);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to update order status']);
}

/**
 * Send delivery confirmation email to customer
 */
function sendDeliveryEmail($order, $connection) {
    try {
        // Load email service
        require_once __DIR__ . '/../classes/DirectSMTPService.php';
        $emailService = new DirectSMTPService();
        
        $customer_email = $order['email'];
        $customer_name = $order['name'];
        $order_id = $order['id'];
        
        $subject = "🎉 Your Order Has Been Delivered!";
        $body = getDeliveryEmailTemplate($customer_name, $order_id);
        
        $result = $emailService->sendEmail($customer_email, $subject, $body, true);
        
        if ($result['success']) {
            error_log("✓ Delivery email sent to: {$customer_email}");
        } else {
            error_log("✗ Delivery email failed to send: {$customer_email} - " . $result['message']);
        }
    } catch (Exception $e) {
        error_log("Error sending delivery email: " . $e->getMessage());
    }
}

/**
 * Get delivery confirmation email template
 */
function getDeliveryEmailTemplate($customer_name, $order_id) {
    return "
    <!DOCTYPE html>
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; color: #333; }
            .container { max-width: 600px; margin: 0 auto; }
            .header { background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%); color: white; padding: 30px; text-align: center; border-radius: 5px 5px 0 0; }
            .header h1 { margin: 0; font-size: 28px; }
            .content { padding: 30px; background-color: #f9f9f9; border-left: 4px solid #4CAF50; }
            .order-details { background: white; padding: 20px; margin: 20px 0; border-radius: 5px; border: 1px solid #ddd; }
            .detail-row { display: flex; padding: 12px 0; border-bottom: 1px solid #eee; }
            .detail-row:last-child { border-bottom: none; }
            .detail-label { flex: 1; font-weight: bold; color: #555; }
            .detail-value { flex: 2; color: #333; }
            .status-badge { background-color: #4CAF50; color: white; padding: 8px 16px; border-radius: 20px; display: inline-block; margin: 10px 0; }
            .footer { background-color: #333; color: white; padding: 20px; text-align: center; font-size: 12px; border-radius: 0 0 5px 5px; }
            .cta { background-color: #4CAF50; color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; display: inline-block; margin: 15px 0; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h1>🎉 Your Order Has Been Delivered!</h1>
            </div>
            <div class='content'>
                <p>Hello <strong>$customer_name</strong>,</p>
                
                <p>Great news! Your order has been <span class='status-badge'>DELIVERED</span>.</p>
                
                <p>We hope you're satisfied with your purchase. Your order details are below:</p>
                
                <div class='order-details'>
                    <div class='detail-row'>
                        <div class='detail-label'>Order ID:</div>
                        <div class='detail-value'>#$order_id</div>
                    </div>
                    <div class='detail-row'>
                        <div class='detail-label'>Status:</div>
                        <div class='detail-value'><strong style='color: #4CAF50;'>✓ Delivered</strong></div>
                    </div>
                </div>
                
                <p>If you have any questions about your order or need any assistance, please don't hesitate to contact us.</p>
                
                <p>Thank you for shopping with us!</p>
                
                <p><strong>Best regards,</strong><br>Interior Design Solutions Team</p>
            </div>
            <div class='footer'>
                <p>&copy; 2026 Interior Design Solutions. All rights reserved.</p>
            </div>
        </div>
    </body>
    </html>
    ";
}

$stmt->close();
$order_stmt->close();
$connection->close();
?>

