<?php
/**
 * Cancel Order API - WITH PENALTY SYSTEM VIA WALLETPROCESSOR
 * File: api/cancel-order.php
 * 
 * UPDATED: Uses WalletProcessor for all wallet transactions
 * Penalty applies ONLY when customer cancels
 */

ob_start();
error_reporting(0);
ini_set('display_errors', '0');

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

ob_clean();
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;
$cancelled_by = $_POST['cancelled_by'] ?? '';
$reason = trim($_POST['reason'] ?? '');

if (empty($reason)) {
    echo json_encode(['success' => false, 'error' => 'Cancellation reason is required']);
    exit;
}

try {
    $db = Database::getInstance();
    $user_id = Auth::id();
    $user_type = Auth::userType();
    
    // Get order details
    $order = $db->fetch("
        SELECT o.*, i.title as item_title, 
        v.id as vendor_id, 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");
    }
    
    if ($order['status'] === 'cancelled') {
        throw new Exception("Order already cancelled");
    }
    
    if ($order['status'] === 'completed' || $order['rental_completed'] == 1) {
        throw new Exception("Cannot cancel completed order");
    }
    
    // Verify permissions
    if ($cancelled_by === 'customer' && ($user_type !== 'customer' || $order['customer_user_id'] != $user_id)) {
        throw new Exception("Unauthorized - not your order");
    }
    
    if ($cancelled_by === 'vendor' && ($user_type !== 'vendor' || $order['vendor_user_id'] != $user_id)) {
        throw new Exception("Unauthorized - not your order");
    }
    
    if ($cancelled_by === 'admin' && $user_type !== 'admin') {
        throw new Exception("Unauthorized - admin access required");
    }
    
    // Get canceller name
    $cancelled_by_name = '';
    if ($cancelled_by === 'customer') {
        $cancelled_by_name = $order['customer_name'];
    } elseif ($cancelled_by === 'vendor') {
        $cancelled_by_name = $order['vendor_name'];
    } elseif ($cancelled_by === 'admin') {
        $admin_user = $db->fetch("
            SELECT CONCAT(COALESCE(c.first_name, v.business_name, 'Admin'), ' ', COALESCE(c.last_name, '')) as name
            FROM users u
            LEFT JOIN customers c ON u.id = c.user_id
            LEFT JOIN vendors v ON u.id = v.user_id
            WHERE u.id = ?
        ", [$user_id]);
        $cancelled_by_name = $admin_user['name'] ?? 'Admin';
    }
    
    // ================================================================
    // PENALTY CALCULATION (ONLY FOR CUSTOMER CANCELLATIONS)
    // ================================================================
    
    $penalty_amount = 0;
    $admin_penalty_share = 0;
    $vendor_penalty_share = 0;
    $refund_amount = 0;
    $penalty_percentage = 0;
    $penalty_timing = '';
    $has_penalty = false;
    
    // Check if order is paid
    $is_paid = ($order['payment_status'] === 'paid');
    
    if ($cancelled_by === 'customer' && $is_paid) {
        // CUSTOMER CANCELLATION - APPLY PENALTY
        
        // Initialize penalty model
        $penaltyModel = new PenaltySettings();
        
        // Rental amount (excluding security deposit)
        $rental_amount = floatval($order['subtotal']);
        $security_deposit = floatval($order['security_deposit']);
        
        // Calculate penalty
        $penalty_calculation = $penaltyModel->calculatePenalty(
            $rental_amount,
            $order['start_date'],
            $order['vendor_id']
        );
        
        $penalty_amount = $penalty_calculation['penalty_amount'];
        $admin_penalty_share = $penalty_calculation['admin_share'];
        $vendor_penalty_share = $penalty_calculation['vendor_share'];
        $penalty_percentage = $penalty_calculation['penalty_percentage'];
        $penalty_timing = $penalty_calculation['timing'];
        
        // Calculate refund = (Rental - Penalty) + Security Deposit
        $refund_amount = ($rental_amount - $penalty_amount) + $security_deposit;
        
        $has_penalty = ($penalty_amount > 0);
        
    } else {
        // VENDOR/ADMIN CANCELLATION - FULL REFUND (NO PENALTY)
        $refund_amount = floatval($order['total_amount']);
    }
    
    // Build cancel_detail JSON
    $cancel_detail = json_encode([
        'cancelled_by' => $cancelled_by,
        'cancelled_by_name' => $cancelled_by_name,
        'reason' => $reason,
        'cancelled_at' => date('Y-m-d H:i:s'),
        'penalty_applied' => $has_penalty
    ]);
    
    $db->beginTransaction();
    
    try {
        // Update order with penalty info
        $db->execute("
            UPDATE orders 
            SET status = 'cancelled', 
                cancelled_at = NOW(),
                cancelled_by = ?,
                cancellation_reason = ?,
                cancel_detail = ?,
                cancellation_fee = ?,
                cancellation_fee_to_vendor = ?,
                cancellation_fee_to_admin = ?,
                refund_amount = ?,
                updated_at = NOW() 
            WHERE id = ?
        ", [
            $user_id,
            $reason,
            $cancel_detail,
            $penalty_amount,
            $vendor_penalty_share,
            $admin_penalty_share,
            $refund_amount,
            $order_id
        ]);
        
        // ================================================================
        // PROCESS REFUND VIA WALLETPROCESSOR
        // ================================================================
        
        if ($is_paid) {
            $walletProcessor = new WalletProcessor();
            
            if ($has_penalty) {
                // CUSTOMER CANCELLATION WITH PENALTY
                $penalty_data = [
                    'penalty_amount' => $penalty_amount,
                    'vendor_share' => $vendor_penalty_share,
                    'admin_share' => $admin_penalty_share,
                    'refund_amount' => $refund_amount
                ];
                
                if (!$walletProcessor->processCancellationWithPenalty($order_id, $penalty_data)) {
                    throw new Exception("Wallet refund processing with penalty failed");
                }
            } else {
                // ADMIN/VENDOR CANCELLATION OR FREE CANCELLATION (NO PENALTY)
                if (!$walletProcessor->processCancellation($order_id)) {
                    throw new Exception("Wallet refund processing failed");
                }
            }
        }
        
        $db->commit();
        
        // ================================================================
        // SEND EMAILS
        // ================================================================
        try {
            $mailer = new Mailer();
            
            $cancelInfo = [
                'cancelled_by' => $cancelled_by,
                'cancelled_by_name' => $cancelled_by_name,
                'reason' => $reason
            ];
            
            $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'],
                'rental_amount' => floatval($order['subtotal']),
                'security_deposit' => floatval($order['security_deposit']),
                'penalty_percentage' => $penalty_percentage,
                'penalty_amount' => $penalty_amount,
                'refund_amount' => $refund_amount,
                'timing' => $penalty_timing,
                'vendor_penalty_earned' => $vendor_penalty_share
            ];
            
            // Send to customer (different email based on penalty)
            if ($has_penalty) {
                // Customer cancellation with penalty
                @$mailer->sendOrderCancellationWithPenalty($orderData);
            } else {
                // No penalty (admin/vendor cancellation or free cancellation period)
                @$mailer->sendOrderCancellationCustomer($orderData, $cancelInfo);
            }
            
            // Send to vendor
            @$mailer->sendOrderCancellationVendor($orderData, $cancelInfo);
            
        } catch (Exception $e) {
            // Don't fail on email errors
            error_log("Cancellation email error: " . $e->getMessage());
        }
        
        // Success response
        $response = [
            'success' => true,
            'message' => 'Order cancelled successfully'
        ];
        
        if ($is_paid) {
            if ($has_penalty) {
                $response['message'] = "Order cancelled. Penalty: ₦" . number_format($penalty_amount, 2) . " | Refund: ₦" . number_format($refund_amount, 2);
            } else {
                $response['message'] = "Order cancelled. Full refund: ₦" . number_format($refund_amount, 2);
            }
        }
        
        echo json_encode($response);
        
    } catch (Exception $e) {
        $db->rollback();
        throw $e;
    }
    
} catch (Exception $e) {
    if (isset($db) && $db->inTransaction()) {
        $db->rollback();
    }
    
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}