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

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

// Rights checking removed - will be implemented later

// Check if adjustment ID is provided
if (!isset($_GET['adjustment_id']) || !is_numeric($_GET['adjustment_id'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid adjustment ID']);
    exit();
}

$adjustment_id = intval($_GET['adjustment_id']);

try {
    // Get adjustment header
    $header_query = "
        SELECT 
            sa.*,
            s.store_name,
            u.username as created_by
        FROM stock_adjustments sa
        LEFT JOIN stores s ON sa.store_id = s.id
        LEFT JOIN users u ON sa.created_by = u.id
        WHERE sa.id = ?
    ";
    
    $header_stmt = $conn->prepare($header_query);
    $header_stmt->bind_param("i", $adjustment_id);
    $header_stmt->execute();
    $adjustment = $header_stmt->get_result()->fetch_assoc();
    
    if (!$adjustment) {
        throw new Exception('Adjustment not found');
    }
    
    // Get adjustment items
    $items_query = "
        SELECT 
            sai.*,
            i.item_role
        FROM stock_adjustment_items sai
        LEFT JOIN items i ON sai.item_id = i.id
        WHERE sai.adjustment_id = ?
        ORDER BY sai.item_name ASC
    ";
    
    $items_stmt = $conn->prepare($items_query);
    $items_stmt->bind_param("i", $adjustment_id);
    $items_stmt->execute();
    $items_result = $items_stmt->get_result();
    
    // Build HTML content
    $html = '
    <div class="adjustment-details">
        <!-- Header Information -->
        <div class="header text-center mb-4">
            <h4>Stock Adjustment Details</h4>
            <h5 class="text-primary">' . htmlspecialchars($adjustment['adjustment_number']) . '</h5>
        </div>
        
        <!-- Summary Information -->
        <div class="summary">
            <div class="row">
                <div class="col-md-6">
                    <table class="table table-borderless">
                        <tr>
                            <td><strong>Adjustment Date:</strong></td>
                            <td>' . date('F d, Y H:i:s', strtotime($adjustment['adjustment_date'])) . '</td>
                        </tr>
                        <tr>
                            <td><strong>Store:</strong></td>
                            <td>' . htmlspecialchars($adjustment['store_name']) . '</td>
                        </tr>
                        <tr>
                            <td><strong>Created By:</strong></td>
                            <td>' . htmlspecialchars($adjustment['created_by']) . '</td>
                        </tr>
                    </table>
                </div>
                <div class="col-md-6">
                    <table class="table table-borderless">
                        <tr>
                            <td><strong>Total Items:</strong></td>
                            <td class="text-end">' . number_format($adjustment['total_items']) . '</td>
                        </tr>
                        <tr>
                            <td><strong>Total Adjustment Value:</strong></td>
                            <td class="text-end">' . ($adjustment['total_adjustment_value'] > 0 ? '+' : '') . number_format($adjustment['total_adjustment_value'], 2) . '</td>
                        </tr>
                        <tr>
                            <td><strong>Current Stock Value:</strong></td>
                            <td class="text-end">' . number_format($adjustment['total_current_stock_value'], 2) . '</td>
                        </tr>
                        <tr>
                            <td><strong>New Stock Value:</strong></td>
                            <td class="text-end">' . number_format($adjustment['total_new_stock_value'], 2) . '</td>
                        </tr>
                    </table>
                </div>
            </div>';
    
    if ($adjustment['remarks']) {
        $html .= '
            <div class="row mt-3">
                <div class="col-12">
                    <strong>Remarks:</strong><br>
                    <em>' . htmlspecialchars($adjustment['remarks']) . '</em>
                </div>
            </div>';
    }
    
    $html .= '</div>
        
        <!-- Items Table -->
        <div class="table-responsive">
            <table class="table table-bordered table-hover">
                <thead class="table-light">
                    <tr>
                        <th>Item Name</th>
                        <th class="text-center">Type</th>
                        <th class="text-end">Current Qty</th>
                        <th class="text-end">Adjustment Qty</th>
                        <th class="text-end">New Qty</th>
                        <th class="text-end">Cost Price</th>
                        <th class="text-end">Current Value</th>
                        <th class="text-end">Adjustment Value</th>
                        <th class="text-end">New Value</th>
                    </tr>
                </thead>
                <tbody>';
    
    while ($item = $items_result->fetch_assoc()) {
        $adjustment_value_class = $item['adjustment_value'] > 0 ? 'text-success' : 'text-danger';
        $adjustment_value_sign = $item['adjustment_value'] > 0 ? '+' : '';
        
        $html .= '
            <tr>
                <td><strong>' . htmlspecialchars($item['item_name']) . '</strong></td>
                <td class="text-center">
                    <span class="badge ' . ($item['item_role'] == 'stock' ? 'bg-primary' : 'bg-success') . '">
                        ' . ucfirst($item['item_role']) . '
                    </span>
                </td>
                <td class="text-end">' . number_format($item['current_quantity'], 2) . '</td>
                <td class="text-end ' . $adjustment_value_class . '">
                    ' . $adjustment_value_sign . number_format($item['adjustment_quantity'], 2) . '
                </td>
                <td class="text-end">' . number_format($item['new_quantity'], 2) . '</td>
                <td class="text-end">' . number_format($item['cost_price'], 2) . '</td>
                <td class="text-end">' . number_format($item['current_stock_value'], 2) . '</td>
                <td class="text-end ' . $adjustment_value_class . '">
                    ' . $adjustment_value_sign . number_format($item['adjustment_value'], 2) . '
                </td>
                <td class="text-end">' . number_format($item['new_stock_value'], 2) . '</td>
            </tr>';
    }
    
    $html .= '
                </tbody>
            </table>
        </div>
        
        <!-- Footer -->
        <div class="text-center mt-4">
            <small class="text-muted">
                Generated on: ' . date('F d, Y H:i:s') . '<br>
                User: ' . htmlspecialchars($_SESSION['username'] ?? 'Unknown') . '
            </small>
        </div>
    </div>';
    
    // Return success response
    echo json_encode([
        'success' => true,
        'html' => $html
    ]);
    
} catch (Exception $e) {
    error_log('Error getting adjustment details: ' . $e->getMessage());
    
    $response = [
        'success' => false,
        'message' => 'Failed to load adjustment details: ' . $e->getMessage()
    ];
    
    http_response_code(500);
    echo json_encode($response);
    
} finally {
    // Close prepared statements
    if (isset($header_stmt)) $header_stmt->close();
    if (isset($items_stmt)) $items_stmt->close();
}


?>
