<?php
/**
 * VENDOR ORDER CANCELLATION PAGE
 * File: modules/vendor/order-cancel.php
 * Cancel orders with reason
 */

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

// Require vendor authentication
Auth::requireVendor();

// Get order ID and reason
$order_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$reason = $_GET['reason'] ?? '';

if (!$order_id) {
    flash('error', 'Invalid order ID', 'danger');
    redirect('orders.php');
}

// Initialize models
$db = Database::getInstance();
$vendor = new Vendor();

// Get vendor details
$vendor_id = Auth::id();
$vendor_data = $vendor->getByUserId($vendor_id);

if (!$vendor_data) {
    flash('error', 'Please complete your profile first.', 'danger');
    redirect('profile.php');
}

// Get order details - ensure it belongs to the current vendor
$order_sql = "SELECT o.*, i.title as item_title 
              FROM orders o 
              JOIN items i ON o.item_id = i.id 
              WHERE o.id = ? AND o.vendor_id = ?";
$order = $db->fetch($order_sql, [$order_id, $vendor_data['id']]);

if (!$order) {
    flash('error', 'Order not found or you do not have permission to cancel it', 'danger');
    redirect('orders.php');
}

// Check if order can be cancelled (only pending or confirmed orders)
$cancellable_statuses = ['pending', 'confirmed'];
if (!in_array($order['status'], $cancellable_statuses)) {
    flash('error', 'This order cannot be cancelled. Only pending or confirmed orders can be cancelled.', 'danger');
    redirect('order-details.php?id=' . $order_id);
}

// Handle cancellation
try {
    $db->beginTransaction();
    
    // Update order status
    $update_sql = "UPDATE orders 
                   SET status = 'cancelled',
                       cancellation_reason = ?,
                       cancelled_by = 'vendor',
                       cancelled_at = NOW(),
                       updated_at = NOW()
                   WHERE id = ?";
    $result = $db->execute($update_sql, [$reason, $order_id]);
    
    if ($result) {
        // Add to order history
        $history_sql = "INSERT INTO order_history (order_id, status, notes, created_by) 
                       VALUES (?, 'cancelled', ?, ?)";
        $notes = "Order cancelled by vendor. Reason: " . $reason;
        $db->execute($history_sql, [$order_id, $notes, 'vendor:' . $vendor_data['id']]);
        
        // If payment was made, process refund (you'll need to implement payment gateway refund)
        if ($order['payment_status'] === 'paid') {
            // Here you would integrate with your payment gateway for refund
            // For now, we'll just update the payment status
            $payment_sql = "UPDATE payments 
                           SET status = 'refunded',
                               refunded_at = NOW(),
                               refund_reason = ?
                           WHERE order_id = ? AND status = 'completed'";
            $db->execute($payment_sql, ["Order cancelled by vendor: " . $reason, $order_id]);
            
            // Update order payment status
            $db->execute("UPDATE orders SET payment_status = 'refunded' WHERE id = ?", [$order_id]);
        }
        
        // Send notification to customer (if notification system exists)
        // $notification = new NotificationService();
        // $notification->send(
        //     $order['customer_id'],
        //     'Order Cancelled',
        //     "Your order #{$order['order_number']} for '{$order['item_title']}' has been cancelled by the vendor. Reason: {$reason}",
        //     'warning',
        //     'customer'
        // );
        
        $db->commit();
        
        // Log the cancellation
        log_message("Vendor {$vendor_data['business_name']} cancelled order #{$order['order_number']}. Reason: {$reason}", 'info');
        
        flash('success', 'Order cancelled successfully!', 'success');
    } else {
        throw new Exception('Failed to update order status');
    }
    
} catch (Exception $e) {
    $db->rollBack();
    log_message("Order cancellation failed: " . $e->getMessage(), 'error');
    flash('error', 'Failed to cancel order: ' . $e->getMessage(), 'danger');
}

// Redirect back to order details
redirect('order-details.php?id=' . $order_id);
?>