<?php
/**
 * Customer Order Completion Request - FIXED
 * File: api/customer-complete-order.php
 * Customer notifies that order can be completed
 */

require_once '../app/Core/init.php';

// CRITICAL: Prevent any output before JSON
ob_start();

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

if (!Auth::check() || !Auth::isCustomer()) {
    ob_end_clean();
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

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

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

try {
    $db = Database::getInstance();
    $customer_user_id = Auth::getUserId();
    
    // Get customer ID
    $customer_sql = "SELECT id FROM customers WHERE user_id = ?";
    $customer = $db->fetch($customer_sql, [$customer_user_id]);
    
    if (!$customer) {
        throw new Exception("Customer not found");
    }
    
    // Get order details
    $order_sql = "SELECT o.*, 
                  i.title as item_title,
                  v.business_name as vendor_name,
                  vu.id as vendor_user_id, vu.email as vendor_email,
                  CONCAT(c.first_name, ' ', c.last_name) as customer_name,
                  cu.email as customer_email
                  FROM orders o
                  JOIN items i ON o.item_id = i.id
                  JOIN vendors v ON o.vendor_id = v.id
                  JOIN users vu ON v.user_id = vu.id
                  JOIN customers c ON o.customer_id = c.id
                  JOIN users cu ON c.user_id = cu.id
                  WHERE o.id = ? AND o.customer_id = ?";
    
    $order = $db->fetch($order_sql, [$order_id, $customer['id']]);
    
    if (!$order) {
        throw new Exception("Order not found");
    }
    
    // Check if already completed
    if ($order['rental_completed'] == 1) {
        throw new Exception("Order is already completed");
    }
    
    // Check if already requested
    if ($order['customer_completion_request'] == 1) {
        throw new Exception("Completion already requested");
    }
    
    // Update order with completion request
    $db->execute(
        "UPDATE orders 
         SET customer_completion_request = 1, 
             customer_completion_time = NOW(),
             updated_at = NOW()
         WHERE id = ?",
        [$order_id]
    );
    
    // Log status history
    $db->execute(
        "INSERT INTO order_status_history 
         (order_id, old_status, new_status, changed_by_type, changed_by_id, reason, created_at)
         VALUES (?, ?, ?, 'customer', ?, 'Customer requested order completion', NOW())",
        [$order_id, $order['status'], 'completion_requested', $customer_user_id]
    );
    
    // Send email to vendor - WRAPPED IN TRY-CATCH
    try {
        $mailer = new Mailer();
        
        $vendor_subject = "Order Completion Request - {$order['order_number']}";
        $vendor_body = "
        <h2>Order Completion Requested</h2>
        <p>Dear {$order['vendor_name']},</p>
        <p>The customer <strong>{$order['customer_name']}</strong> has indicated that the rental order is complete and ready for final processing.</p>
        
        <div style='background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0;'>
            <h3>Order Details</h3>
            <p><strong>Order Number:</strong> {$order['order_number']}</p>
            <p><strong>Item:</strong> {$order['item_title']}</p>
            <p><strong>Rental Period:</strong> {$order['start_date']} to {$order['end_date']}</p>
        </div>
        
        <div style='background: #fff3cd; padding: 15px; border-radius: 8px; margin: 20px 0;'>
            <h4>Action Required</h4>
            <p>Please review the returned item and complete the order in your vendor dashboard to:</p>
            <ul>
                <li>Release the security deposit to the customer</li>
                <li>Receive your rental payment (minus platform fee)</li>
                <li>Close the order</li>
            </ul>
        </div>
        
        <p>Please login to your vendor dashboard to complete this order.</p>
        ";
        
        $mailer->send($order['vendor_email'], $vendor_subject, $vendor_body);
        
        // Send email to admin
        $admin_email = defined('ADMIN_EMAIL') ? ADMIN_EMAIL : 'admin@rentidium.ng';
        $admin_subject = "Order Completion Request - {$order['order_number']}";
        $admin_body = "
        <h2>Order Completion Requested</h2>
        <p>Customer <strong>{$order['customer_name']}</strong> has requested completion for order <strong>{$order['order_number']}</strong>.</p>
        <p><strong>Item:</strong> {$order['item_title']}</p>
        <p><strong>Vendor:</strong> {$order['vendor_name']}</p>
        <p>Please review in admin dashboard.</p>
        ";
        
        $mailer->send($admin_email, $admin_subject, $admin_body);
        
    } catch (Exception $email_error) {
        // Log email error but don't fail the request
        error_log("Email sending failed in customer-complete-order: " . $email_error->getMessage());
        // Continue - the important part (DB update) succeeded
    }
    
    // Clean output buffer and send success
    ob_end_clean();
    
    echo json_encode([
        'success' => true,
        'message' => 'Completion request sent successfully. Vendor will be notified to complete the order.'
    ]);
    
} catch (Exception $e) {
    ob_end_clean();
    error_log("Customer completion request error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}