<?php
session_start();
include '../db.php';

// Set content type to JSON
header('Content-Type: application/json');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'User not authenticated']);
    exit;
}

$purchase_id = intval($_GET['id'] ?? 0);
$store_id = $_SESSION['store_id'] ?? 1;

if (!$purchase_id) {
    echo json_encode(['success' => false, 'message' => 'Invalid purchase ID']);
    exit;
}

try {
    // Check database connection
    if ($conn->connect_error) {
        throw new Exception('Database connection failed: ' . $conn->connect_error);
    }
    
    // Get purchase header with supplier information
    $purchase_stmt = $conn->prepare("
        SELECT 
            p.*,
            v.name AS supplier_name,
            v.contact_number,
            v.email,
            v.address
        FROM purchases p
        JOIN vendors v ON p.vendor_id = v.id
        WHERE p.id = ? AND (p.store_id = ? OR p.store_id IS NULL)
    ");
    
    if (!$purchase_stmt) {
        throw new Exception('Prepare failed: ' . $conn->error);
    }
    
    $purchase_stmt->bind_param("ii", $purchase_id, $store_id);
    $purchase_stmt->execute();
    $purchase = $purchase_stmt->get_result()->fetch_assoc();
    
    if (!$purchase) {
        echo json_encode(['success' => false, 'message' => 'Purchase not found']);
        exit;
    }
    
    // Get purchase items
    $items_stmt = $conn->prepare("
        SELECT 
            pi.*,
            i.item_code,
            i.retail_price
        FROM purchase_items pi
        LEFT JOIN items i ON pi.item_id = i.id
        WHERE pi.purchase_id = ? 
        ORDER BY pi.id
    ");
    
    // Get purchase returns information
    $returns_stmt = $conn->prepare("
        SELECT 
            pr.*,
            COUNT(pri.id) as item_count
        FROM purchase_returns pr
        LEFT JOIN purchase_return_items pri ON pr.id = pri.purchase_return_id
        WHERE pr.purchase_id = ?
        GROUP BY pr.id
        ORDER BY pr.return_date DESC
    ");
    
    if (!$items_stmt) {
        throw new Exception('Items prepare failed: ' . $conn->error);
    }
    
    if (!$returns_stmt) {
        throw new Exception('Returns prepare failed: ' . $conn->error);
    }
    
    $items_stmt->bind_param("i", $purchase_id);
    $items_stmt->execute();
    $items_result = $items_stmt->get_result();
    
    $returns_stmt->bind_param("i", $purchase_id);
    $returns_stmt->execute();
    $returns_result = $returns_stmt->get_result();
    
    $items = [];
    while ($item = $items_result->fetch_assoc()) {
        $items[] = $item;
    }
    
    $returns = [];
    while ($return = $returns_result->fetch_assoc()) {
        $returns[] = $return;
    }
    
    // Generate HTML for the modal
    $html = generatePurchaseHTML($purchase, $items, $returns);
    
    $response = [
        'success' => true,
        'html' => $html,
        'purchase' => $purchase,
        'items' => $items,
        'returns' => $returns
    ];
    
    // Ensure no output before JSON
    if (ob_get_level()) {
        ob_clean();
    }
    
    echo json_encode($response);
    
} catch (Exception $e) {
    error_log('Purchase details error: ' . $e->getMessage());
    
    // Ensure no output before JSON
    if (ob_get_level()) {
        ob_clean();
    }
    
    echo json_encode([
        'success' => false,
        'message' => 'Error fetching purchase details: ' . $e->getMessage()
    ]);
}

function generatePurchaseHTML($purchase, $items, $returns = []) {
    $status_badge_class = $purchase['status'] === 'received' ? 'bg-success' : 'bg-warning';
    $status_text = ucfirst($purchase['status']);
    
    $html = '
    <div class="row">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h6 class="mb-0"><i class="fas fa-shopping-cart me-2"></i>Purchase Information</h6>
                </div>
                <div class="card-body">
                    <div class="row mb-2">
                        <div class="col-4"><strong>Purchase #:</strong></div>
                        <div class="col-8">' . htmlspecialchars($purchase['purchase_number']) . '</div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-4"><strong>Date:</strong></div>
                        <div class="col-8">' . date('M d, Y H:i', strtotime($purchase['purchase_date'])) . '</div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-4"><strong>Status:</strong></div>
                        <div class="col-8"><span class="badge ' . $status_badge_class . '">' . $status_text . '</span></div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-4"><strong>Payment:</strong></div>
                        <div class="col-8">' . ucfirst($purchase['payment_method']) . '</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card">
                <div class="card-header bg-info text-white">
                    <h6 class="mb-0"><i class="fas fa-building me-2"></i>Supplier Information</h6>
                </div>
                <div class="card-body">
                    <div class="row mb-2">
                        <div class="col-4"><strong>Name:</strong></div>
                        <div class="col-8">' . htmlspecialchars($purchase['supplier_name']) . '</div>
                    </div>';
    
    if (!empty($purchase['contact_number'])) {
        $html .= '
                    <div class="row mb-2">
                        <div class="col-4"><strong>Phone:</strong></div>
                        <div class="col-8">' . htmlspecialchars($purchase['contact_number']) . '</div>
                    </div>';
    }
    
    if (!empty($purchase['email'])) {
        $html .= '
                    <div class="row mb-2">
                        <div class="col-4"><strong>Email:</strong></div>
                        <div class="col-8">' . htmlspecialchars($purchase['email']) . '</div>
                    </div>';
    }
    
    $html .= '
                </div>
            </div>
        </div>
    </div>
    
    <div class="row mt-3">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-secondary text-white">
                    <h6 class="mb-0"><i class="fas fa-list me-2"></i>Purchase Items</h6>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover mb-0">
                            <thead class="table-dark">
                                <tr>
                                    <th>Item Name</th>
                                    <th>Item Code</th>
                                    <th class="text-center">Qty</th>
                                    <th class="text-end">Unit Cost</th>
                                    <th class="text-end">Tax Rate</th>
                                    <th class="text-end">Total Cost</th>
                                </tr>
                            </thead>
                            <tbody>';
    
    $subtotal = 0;
    $total_tax = 0;
    
    foreach ($items as $item) {
        $item_total = $item['quantity'] * $item['unit_cost'];
        $tax_amount = ($item['tax_rate'] / 100) * $item_total;
        $subtotal += $item_total;
        $total_tax += $tax_amount;
        
        $html .= '
                                <tr>
                                    <td>' . htmlspecialchars($item['item_name']) . '</td>
                                    <td>' . htmlspecialchars($item['item_code'] ?? 'N/A') . '</td>
                                    <td class="text-center">' . $item['quantity'] . '</td>
                                    <td class="text-end">Rs ' . number_format($item['unit_cost'], 2) . '</td>
                                    <td class="text-end">' . number_format($item['tax_rate'], 2) . '%</td>
                                    <td class="text-end">Rs ' . number_format($item_total, 2) . '</td>
                                </tr>';
    }
    
    $html .= '
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="row mt-3">
        <div class="col-md-6"></div>
        <div class="col-md-6">
            <div class="card">
                <div class="card-body">
                    <div class="row mb-2">
                        <div class="col-6"><strong>Subtotal:</strong></div>
                        <div class="col-6 text-end">Rs ' . number_format($subtotal, 2) . '</div>
                    </div>
                    <div class="row mb-2">
                        <div class="col-6"><strong>Tax Amount:</strong></div>
                        <div class="col-6 text-end">Rs ' . number_format($purchase['tax_amount'], 2) . '</div>
                    </div>';
    
    if ($purchase['discount_amount'] > 0) {
        $html .= '
                    <div class="row mb-2">
                        <div class="col-6"><strong>Discount:</strong></div>
                        <div class="col-6 text-end text-danger">-Rs ' . number_format($purchase['discount_amount'], 2) . '</div>
                    </div>';
    }
    
    $html .= '
                    <hr>
                    <div class="row">
                        <div class="col-6"><strong>Net Total:</strong></div>
                        <div class="col-6 text-end"><strong>Rs ' . number_format($purchase['net_amount'], 2) . '</strong></div>
                    </div>
                </div>
            </div>
        </div>
    </div>';
    
    // Add return history section if there are returns
    if (!empty($returns)) {
        $total_return_amount = array_sum(array_column($returns, 'total_amount'));
        $return_percentage = ($total_return_amount / $purchase['total_amount']) * 100;
        
        $html .= '
    <div class="row mt-3">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-warning text-dark">
                    <h6 class="mb-0">
                        <i class="fas fa-undo me-2"></i>Return History
                        <span class="badge bg-light text-dark ms-2">' . count($returns) . ' Return(s) - Rs ' . number_format($total_return_amount, 2) . '</span>
                    </h6>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>Return Date</th>
                                    <th>Return Amount</th>
                                    <th>Items Returned</th>
                                    <th>Remarks</th>
                                </tr>
                            </thead>
                            <tbody>';
        
        foreach ($returns as $return) {
            $html .= '
                                <tr>
                                    <td>' . date('M d, Y H:i', strtotime($return['return_date'])) . '</td>
                                    <td><strong>Rs ' . number_format($return['total_amount'], 2) . '</strong></td>
                                    <td>' . $return['item_count'] . ' item(s)</td>
                                    <td>' . htmlspecialchars($return['customer_remarks'] ?: 'No remarks') . '</td>
                                </tr>';
        }
        
        $html .= '
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>';
    }
    
    return $html;
}
?>
