<?php
include '../db.php';
include '../auth.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

// Get void ID
$void_id = $_GET['void_id'] ?? null;

if (!$void_id) {
    echo json_encode(['status' => 'error', 'message' => 'Void ID is required']);
    exit;
}

try {
    // Get void order details
    $stmt = $conn->prepare("
        SELECT 
            vo.*,
            s.invoice_number,
            s.customer_name,
            s.sale_date,
            s.total_amount,
            s.net_amount,
            vr.reason_name as void_reason,
            u.username as voided_by_user
        FROM void_orders vo
        LEFT JOIN sales s ON vo.sale_id = s.id
        LEFT JOIN void_reasons vr ON vo.void_reason_id = vr.id
        LEFT JOIN users u ON vo.voided_by = u.id
        WHERE vo.id = ?
    ");
    
    $stmt->bind_param("i", $void_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        echo json_encode(['status' => 'error', 'message' => 'Void order not found']);
        exit;
    }
    
    $void_order = $result->fetch_assoc();
    
    // Get sale items (if any were saved)
    $stmt = $conn->prepare("
        SELECT 
            si.*,
            i.name as item_name,
            i.retail_price
        FROM sale_items si
        LEFT JOIN items i ON si.item_id = i.id
        WHERE si.sale_id = ?
    ");
    
    $stmt->bind_param("i", $void_order['sale_id']);
    $stmt->execute();
    $items_result = $stmt->get_result();
    
    $items = [];
    while ($item = $items_result->fetch_assoc()) {
        $items[] = $item;
    }
    
    // Generate HTML
    $html = '
    <div data-void-id="' . $void_order['id'] . '">
        <div class="row">
            <div class="col-md-6">
                <h6 class="text-muted mb-2">Void Information</h6>
                <table class="table table-sm">
                    <tr>
                        <td><strong>Void ID:</strong></td>
                        <td><span class="badge bg-danger">#' . $void_order['id'] . '</span></td>
                    </tr>
                    <tr>
                        <td><strong>Sale ID:</strong></td>
                        <td><span class="badge bg-secondary">#' . $void_order['sale_id'] . '</span></td>
                    </tr>
                    <tr>
                        <td><strong>Invoice:</strong></td>
                        <td><strong>' . htmlspecialchars($void_order['invoice_number']) . '</strong></td>
                    </tr>
                    <tr>
                        <td><strong>Customer:</strong></td>
                        <td>' . htmlspecialchars($void_order['customer_name']) . '</td>
                    </tr>
                    <tr>
                        <td><strong>Sale Date:</strong></td>
                        <td>' . date('M d, Y H:i', strtotime($void_order['sale_date'])) . '</td>
                    </tr>
                    <tr>
                        <td><strong>Void Date:</strong></td>
                        <td>' . date('M d, Y H:i', strtotime($void_order['voided_at'])) . '</td>
                    </tr>
                </table>
            </div>
            <div class="col-md-6">
                <h6 class="text-muted mb-2">Void Details</h6>
                <table class="table table-sm">
                    <tr>
                        <td><strong>Void Reason:</strong></td>
                        <td><span class="badge bg-warning">' . htmlspecialchars($void_order['void_reason']) . '</span></td>
                    </tr>
                    <tr>
                        <td><strong>Voided By:</strong></td>
                        <td>' . htmlspecialchars($void_order['voided_by_user']) . '</td>
                    </tr>
                    <tr>
                        <td><strong>Original Amount:</strong></td>
                        <td><strong class="text-danger">Rs ' . number_format($void_order['original_amount'], 2) . '</strong></td>
                    </tr>
                    <tr>
                        <td><strong>Sale Total:</strong></td>
                        <td>Rs ' . number_format($void_order['total_amount'], 2) . '</td>
                    </tr>
                    <tr>
                        <td><strong>Net Amount:</strong></td>
                        <td>Rs ' . number_format($void_order['net_amount'], 2) . '</td>
                    </tr>
                </table>
            </div>
        </div>';
    
    if (!empty($void_order['notes'])) {
        $html .= '
        <div class="row mt-3">
            <div class="col-12">
                <h6 class="text-muted mb-2">Void Notes</h6>
                <div class="alert alert-info">
                    ' . nl2br(htmlspecialchars($void_order['notes'])) . '
                </div>
            </div>
        </div>';
    }
    
    if (!empty($items)) {
        $html .= '
        <div class="row mt-3">
            <div class="col-12">
                <h6 class="text-muted mb-2">Order Items</h6>
                <div class="table-responsive">
                    <table class="table table-sm table-striped">
                        <thead>
                            <tr>
                                <th>Item</th>
                                <th>Qty</th>
                                <th>Price</th>
                                <th>Total</th>
                            </tr>
                        </thead>
                        <tbody>';
        
        foreach ($items as $item) {
            $html .= '
                            <tr>
                                <td>' . htmlspecialchars($item['item_name']) . '</td>
                                <td>' . $item['quantity'] . '</td>
                                <td>Rs ' . number_format($item['unit_price'], 2) . '</td>
                                <td>Rs ' . number_format($item['total_price'], 2) . '</td>
                            </tr>';
        }
        
        $html .= '
                        </tbody>
                    </table>
                </div>
            </div>
        </div>';
    }
    
    $html .= '</div>';
    
    echo json_encode([
        'status' => 'success',
        'html' => $html,
        'data' => $void_order
    ]);
    
} catch (Exception $e) {
    error_log("Error getting void details: " . $e->getMessage());
    echo json_encode(['status' => 'error', 'message' => 'Failed to load void details']);
}
?>
