<?php
/**
 * Complete Rental API - FIXED WITH PROPER WORKFLOW
 * File: api/complete-rental.php
 * 
 * NEW WORKFLOW:
 * - Customer/Vendor can REQUEST completion
 * - Other party must CONFIRM completion
 * - Admin can COMPLETE directly anytime
 */

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

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

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

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

$order_id = $_POST['order_id'] ?? 0;
$action = $_POST['action'] ?? 'complete'; // 'request' or 'confirm' or 'complete'

try {
    $db = Database::getInstance();
    $user_type = Auth::userType();
    $user_id = Auth::id();
    
    // Get order with full details
    $order = $db->fetch("
        SELECT o.*, i.title as item_title,
        v.business_name as vendor_name, v.user_id as vendor_user_id, vu.email as vendor_email,
        CONCAT(c.first_name, ' ', c.last_name) as customer_name, c.user_id as customer_user_id, 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 = ?
    ", [$order_id]);
    
    if (!$order) {
        throw new Exception("Order not found");
    }
    
    // Check permissions
    $is_customer = ($user_type === 'customer' && $order['customer_user_id'] == $user_id);
    $is_vendor = ($user_type === 'vendor' && $order['vendor_user_id'] == $user_id);
    $is_admin = ($user_type === 'admin');
    
    if (!$is_customer && !$is_vendor && !$is_admin) {
        throw new Exception("Unauthorized");
    }
    
    if (!in_array($order['status'], ['ongoing', 'confirmed'])) {
        throw new Exception("Order cannot be completed (status: {$order['status']})");
    }
    
    if ($order['rental_completed'] == 1) {
        throw new Exception("Order already completed");
    }
    
    $db->beginTransaction();
    
    try {
        // ==========================================
        // ADMIN: Can complete directly anytime
        // ==========================================
        if ($is_admin) {
            // Update order status
            $db->execute("
                UPDATE orders 
                SET status = 'completed',
                    rental_completed = 1,
                    customer_completion_request = 0,
                    vendor_completion_request = 0,
                    completed_at = NOW(),
                    completed_by = 'admin',
                    updated_at = NOW()
                WHERE id = ?
            ", [$order_id]);
            
            // Process wallet
            $walletProcessor = new WalletProcessor();
            if (!$walletProcessor->processCompletedOrder($order_id)) {
                throw new Exception("Wallet processing failed");
            }
            
            $db->commit();
            
            // Get amounts for emails
            $breakdowns = $db->fetchAll("
                SELECT * FROM order_payment_breakdown 
                WHERE order_id = ? AND status = 'released'
            ", [$order_id]);
            
            $security_amount = 0;
            $vendor_earning = 0;
            
            foreach ($breakdowns as $breakdown) {
                if ($breakdown['type'] === 'security_deposit') {
                    $security_amount = floatval($breakdown['amount']);
                } elseif ($breakdown['type'] === 'rental') {
                    $vendor_earning = floatval($breakdown['amount']);
                }
            }
            
            // Send emails to both parties
            try {
                $mailer = new Mailer();
                
                $orderData = [
                    'order_number' => $order['order_number'],
                    'customer_name' => $order['customer_name'],
                    'customer_email' => $order['customer_email'],
                    'vendor_name' => $order['vendor_name'],
                    'vendor_email' => $order['vendor_email'],
                    'item_title' => $order['item_title']
                ];
                
                @$mailer->sendOrderCompletionCustomer($orderData, $security_amount);
                @$mailer->sendOrderCompletionVendor($orderData, $vendor_earning);
                
            } catch (Exception $e) {
                error_log("Completion email error: " . $e->getMessage());
            }
            
            echo json_encode([
                'success' => true,
                'message' => 'Order completed by admin. Emails sent to customer and vendor.'
            ]);
            exit;
        }
        
        // ==========================================
        // CUSTOMER/VENDOR: Request or Confirm
        // ==========================================
        
        $customer_requested = $order['customer_completion_request'] ?? 0;
        $vendor_requested = $order['vendor_completion_request'] ?? 0;
        
        if ($is_customer) {
            if ($customer_requested == 1) {
                throw new Exception("You have already requested completion");
            }
            
            if ($vendor_requested == 1) {
                // Vendor requested, customer confirming - COMPLETE ORDER
                $db->execute("
                    UPDATE orders 
                    SET status = 'completed',
                        rental_completed = 1,
                        customer_completion_request = 1,
                        customer_completion_time = NOW(),
                        vendor_completion_request = 0,
                        completed_at = NOW(),
                        completed_by = 'customer_confirmed',
                        updated_at = NOW()
                    WHERE id = ?
                ", [$order_id]);
                
                // Process wallet
                $walletProcessor = new WalletProcessor();
                if (!$walletProcessor->processCompletedOrder($order_id)) {
                    throw new Exception("Wallet processing failed");
                }
                
                $db->commit();
                
                // Get amounts for emails
                $breakdowns = $db->fetchAll("
                    SELECT * FROM order_payment_breakdown 
                    WHERE order_id = ? AND status = 'released'
                ", [$order_id]);
                
                $security_amount = 0;
                $vendor_earning = 0;
                
                foreach ($breakdowns as $breakdown) {
                    if ($breakdown['type'] === 'security_deposit') {
                        $security_amount = floatval($breakdown['amount']);
                    } elseif ($breakdown['type'] === 'rental') {
                        $vendor_earning = floatval($breakdown['amount']);
                    }
                }
                
                // Send emails
                try {
                    $mailer = new Mailer();
                    
                    $orderData = [
                        'order_number' => $order['order_number'],
                        'customer_name' => $order['customer_name'],
                        'customer_email' => $order['customer_email'],
                        'vendor_name' => $order['vendor_name'],
                        'vendor_email' => $order['vendor_email'],
                        'item_title' => $order['item_title']
                    ];
                    
                    @$mailer->sendOrderCompletionCustomer($orderData, $security_amount);
                    @$mailer->sendOrderCompletionVendor($orderData, $vendor_earning);
                    
                } catch (Exception $e) {
                    error_log("Completion email error: " . $e->getMessage());
                }
                
                echo json_encode([
                    'success' => true,
                    'message' => 'Order completed! Vendor requested, you confirmed. Emails sent to both parties.'
                ]);
                exit;
                
            } else {
                // Customer requesting completion
                $db->execute("
                    UPDATE orders 
                    SET customer_completion_request = 1,
                        customer_completion_time = NOW(),
                        updated_at = NOW()
                    WHERE id = ?
                ", [$order_id]);
                
                $db->commit();
                
                echo json_encode([
                    'success' => true,
                    'message' => 'Completion request sent. Waiting for vendor confirmation.'
                ]);
                exit;
            }
        }
        
        if ($is_vendor) {
            if ($vendor_requested == 1) {
                throw new Exception("You have already requested completion");
            }
            
            if ($customer_requested == 1) {
                // Customer requested, vendor confirming - COMPLETE ORDER
                $db->execute("
                    UPDATE orders 
                    SET status = 'completed',
                        rental_completed = 1,
                        customer_completion_request = 0,
                        vendor_completion_request = 1,
                        vendor_completion_time = NOW(),
                        completed_at = NOW(),
                        completed_by = 'vendor_confirmed',
                        updated_at = NOW()
                    WHERE id = ?
                ", [$order_id]);
                
                // Process wallet
                $walletProcessor = new WalletProcessor();
                if (!$walletProcessor->processCompletedOrder($order_id)) {
                    throw new Exception("Wallet processing failed");
                }
                
                $db->commit();
                
                // Get amounts for emails
                $breakdowns = $db->fetchAll("
                    SELECT * FROM order_payment_breakdown 
                    WHERE order_id = ? AND status = 'released'
                ", [$order_id]);
                
                $security_amount = 0;
                $vendor_earning = 0;
                
                foreach ($breakdowns as $breakdown) {
                    if ($breakdown['type'] === 'security_deposit') {
                        $security_amount = floatval($breakdown['amount']);
                    } elseif ($breakdown['type'] === 'rental') {
                        $vendor_earning = floatval($breakdown['amount']);
                    }
                }
                
                // Send emails
                try {
                    $mailer = new Mailer();
                    
                    $orderData = [
                        'order_number' => $order['order_number'],
                        'customer_name' => $order['customer_name'],
                        'customer_email' => $order['customer_email'],
                        'vendor_name' => $order['vendor_name'],
                        'vendor_email' => $order['vendor_email'],
                        'item_title' => $order['item_title']
                    ];
                    
                    @$mailer->sendOrderCompletionCustomer($orderData, $security_amount);
                    @$mailer->sendOrderCompletionVendor($orderData, $vendor_earning);
                    
                } catch (Exception $e) {
                    error_log("Completion email error: " . $e->getMessage());
                }
                
                echo json_encode([
                    'success' => true,
                    'message' => 'Order completed! Customer requested, you confirmed. Emails sent to both parties.'
                ]);
                exit;
                
            } else {
                // Vendor requesting completion
                $db->execute("
                    UPDATE orders 
                    SET vendor_completion_request = 1,
                        vendor_completion_time = NOW(),
                        updated_at = NOW()
                    WHERE id = ?
                ", [$order_id]);
                
                $db->commit();
                
                echo json_encode([
                    'success' => true,
                    'message' => 'Completion request sent. Waiting for customer confirmation.'
                ]);
                exit;
            }
        }
        
    } catch (Exception $e) {
        $db->rollback();
        throw $e;
    }
    
} catch (Exception $e) {
    if (isset($db) && $db->inTransaction()) {
        $db->rollback();
    }
    
    error_log("Complete rental error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}