<!DOCTYPE html>
<?php
include("layout.php");
include("db.php");
include 'functions/video_help.php';

// Rights checking removed - will be implemented later

// Get selected store filter
$selected_store = isset($_GET['store_id']) ? intval($_GET['store_id']) : ($_SESSION['current_store_id'] ?? 1);

// Get all stores for the filter dropdown
$stores_query = "SELECT id, store_name, store_code FROM stores WHERE is_active = 1 ORDER BY store_name";
$stores_result = $conn->query($stores_query);

// Get adjustments with pagination
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$limit = 20;
$offset = ($page - 1) * $limit;

// Build query with filters
$where_conditions = ["1=1"];
$params = [];
$param_types = "";

if ($selected_store > 0) {
    $where_conditions[] = "sa.store_id = ?";
    $params[] = $selected_store;
    $param_types .= "i";
}

$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';

if ($date_from) {
    $where_conditions[] = "DATE(sa.adjustment_date) >= ?";
    $params[] = $date_from;
    $param_types .= "s";
}

if ($date_to) {
    $where_conditions[] = "DATE(sa.adjustment_date) <= ?";
    $params[] = $date_to;
    $param_types .= "s";
}

$where_clause = implode(" AND ", $where_conditions);

// Count total records
$count_query = "
    SELECT COUNT(*) as total 
    FROM stock_adjustments sa
    WHERE $where_clause
";

$count_stmt = $conn->prepare($count_query);
if (!empty($params)) {
    $count_stmt->bind_param($param_types, ...$params);
}
$count_stmt->execute();
$total_records = $count_stmt->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_records / $limit);

// Get adjustments
$query = "
    SELECT 
        sa.id,
        sa.adjustment_number,
        sa.adjustment_date,
        sa.total_items,
        sa.total_adjustment_value,
        sa.total_current_stock_value,
        sa.total_new_stock_value,
        sa.remarks,
        sa.journal_entry_id,
        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 $where_clause
    ORDER BY sa.adjustment_date DESC, sa.id DESC
    LIMIT ? OFFSET ?
";

$params[] = $limit;
$params[] = $offset;
$param_types .= "ii";

$stmt = $conn->prepare($query);
$stmt->bind_param($param_types, ...$params);
$stmt->execute();
$adjustments_result = $stmt->get_result();
?>

<div class="page-wrapper">
    <div class="content">
        <div class="page-header d-flex justify-content-between align-items-center">
            <div class="page-title">
                <h4>Stock Adjustment History</h4>
                <h6>View and track all stock adjustments</h6>
            </div>
            <div class="d-flex gap-2">
                <?= display_video_help_button('stock_adjustment_list', $conn, '<i class="fa fa-play-circle"></i> Watch Video', 'btn-outline-primary') ?>
                <a href="stock_adjustment.php" class="btn btn-primary">
                    <i class="fa fa-plus"></i> New Adjustment
                </a>
            </div>
        </div>

        <!-- Filters -->
        <div class="card mb-3">
            <div class="card-body">
                <form method="GET" action="" class="row align-items-end">
                    <div class="col-md-2">
                        <label for="store_filter" class="form-label">Store</label>
                        <select name="store_id" id="store_filter" class="form-control">
                            <option value="">All Stores</option>
                            <?php while ($store = $stores_result->fetch_assoc()) : ?>
                                <option value="<?= $store['id'] ?>" <?= ($store['id'] == $selected_store) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($store['store_name']) ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="date_from" class="form-label">From Date</label>
                        <input type="date" name="date_from" id="date_from" class="form-control" value="<?= htmlspecialchars($date_from) ?>">
                    </div>
                    <div class="col-md-2">
                        <label for="date_to" class="form-label">To Date</label>
                        <input type="date" name="date_to" id="date_to" class="form-control" value="<?= htmlspecialchars($date_to) ?>">
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fa fa-filter"></i> Filter
                        </button>
                    </div>
                    <div class="col-md-2">
                        <a href="?" class="btn btn-outline-secondary w-100">
                            <i class="fa fa-refresh"></i> Clear
                        </a>
                    </div>
                    <div class="col-md-2">
                        <a href="export_excel.php?report=stock_adjustments&store_id=<?= $selected_store ?>&date_from=<?= $date_from ?>&date_to=<?= $date_to ?>" class="btn btn-success w-100">
                            <i class="fa fa-download"></i> Export
                        </a>
                    </div>
                </form>
            </div>
        </div>

        <!-- Adjustments Table -->
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fa fa-history"></i> Adjustment History
                    <span class="badge bg-primary ms-2"><?= number_format($total_records) ?> records</span>
                </h5>
            </div>
            <div class="card-body">
                <?php if ($total_records > 0) : ?>
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover">
                            <thead class="table-light">
                                <tr>
                                    <th>Adjustment #</th>
                                    <th>Date</th>
                                    <th>Store</th>
                                    <th>Items</th>
                                    <th>Adjustment Value</th>
                                    <th>Current Stock Value</th>
                                    <th>New Stock Value</th>
                                    <th>Journal Entry</th>
                                    <th>Created By</th>
                                    <th>Remarks</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($adjustment = $adjustments_result->fetch_assoc()) : ?>
                                    <tr>
                                        <td>
                                            <strong class="text-primary"><?= htmlspecialchars($adjustment['adjustment_number']) ?></strong>
                                        </td>
                                        <td>
                                            <?= date('M d, Y H:i', strtotime($adjustment['adjustment_date'])) ?>
                                        </td>
                                        <td>
                                            <span class="badge bg-info"><?= htmlspecialchars($adjustment['store_name']) ?></span>
                                        </td>
                                        <td class="text-center">
                                            <span class="badge bg-secondary"><?= $adjustment['total_items'] ?></span>
                                        </td>
                                        <td class="text-end">
                                            <?php if ($adjustment['total_adjustment_value'] > 0) : ?>
                                                <span class="text-success">+<?= number_format($adjustment['total_adjustment_value'], 2) ?></span>
                                            <?php else : ?>
                                                <span class="text-danger"><?= number_format($adjustment['total_adjustment_value'], 2) ?></span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-end">
                                            <?= number_format($adjustment['total_current_stock_value'], 2) ?>
                                        </td>
                                        <td class="text-end">
                                            <?= number_format($adjustment['total_new_stock_value'], 2) ?>
                                        </td>
                                        <td class="text-center">
                                            <?php if ($adjustment['journal_entry_id']) : ?>
                                                <span class="badge bg-success" title="Journal Entry #<?= $adjustment['journal_entry_id'] ?>">
                                                    <i class="fa fa-check"></i> Created
                                                </span>
                                            <?php else : ?>
                                                <span class="badge bg-warning" title="No journal entry created">
                                                    <i class="fa fa-exclamation-triangle"></i> Pending
                                                </span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <small class="text-muted"><?= htmlspecialchars($adjustment['created_by']) ?></small>
                                        </td>
                                        <td>
                                            <?php if ($adjustment['remarks']) : ?>
                                                <span class="text-muted" title="<?= htmlspecialchars($adjustment['remarks']) ?>">
                                                    <?= strlen($adjustment['remarks']) > 30 ? substr($adjustment['remarks'], 0, 30) . '...' : htmlspecialchars($adjustment['remarks']) ?>
                                                </span>
                                            <?php else : ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <button type="button" class="btn btn-outline-info" 
                                                        onclick="viewAdjustmentDetails(<?= $adjustment['id'] ?>)"
                                                        title="View Details">
                                                    <i class="fa fa-eye"></i>
                                                </button>
                                                <a href="stock_adjustment_report.php?adjustment_id=<?= $adjustment['id'] ?>" 
                                                   class="btn btn-outline-success" 
                                                   title="Print Report">
                                                    <i class="fa fa-print"></i>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    <?php if ($total_pages > 1) : ?>
                        <nav aria-label="Adjustment pagination" class="mt-3">
                            <ul class="pagination justify-content-center">
                                <?php if ($page > 1) : ?>
                                    <li class="page-item">
                                        <a class="page-link" href="?page=<?= $page - 1 ?>&store_id=<?= $selected_store ?>&date_from=<?= $date_from ?>&date_to=<?= $date_to ?>">
                                            <i class="fa fa-chevron-left"></i> Previous
                                        </a>
                                    </li>
                                <?php endif; ?>
                                
                                <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++) : ?>
                                    <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                                        <a class="page-link" href="?page=<?= $i ?>&store_id=<?= $selected_store ?>&date_from=<?= $date_from ?>&date_to=<?= $date_to ?>">
                                            <?= $i ?>
                                        </a>
                                    </li>
                                <?php endfor; ?>
                                
                                <?php if ($page < $total_pages) : ?>
                                    <li class="page-item">
                                        <a class="page-link" href="?page=<?= $page + 1 ?>&store_id=<?= $selected_store ?>&date_from=<?= $date_from ?>&date_to=<?= $date_to ?>">
                                            Next <i class="fa fa-chevron-right"></i>
                                        </a>
                                    </li>
                                <?php endif; ?>
                            </ul>
                        </nav>
                    <?php endif; ?>

                <?php else : ?>
                    <div class="text-center py-5">
                        <i class="fa fa-inbox fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted">No adjustments found</h5>
                        <p class="text-muted">No stock adjustments match your current filters.</p>
                        <a href="stock_adjustment.php" class="btn btn-primary">
                            <i class="fa fa-plus"></i> Create First Adjustment
                        </a>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Adjustment Details Modal -->
<div class="modal fade" id="adjustmentDetailsModal" tabindex="-1" aria-labelledby="adjustmentDetailsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="adjustmentDetailsModalLabel">Adjustment Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="adjustmentDetailsContent">
                <!-- Content will be loaded here -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" onclick="printAdjustment()">Print</button>
            </div>
        </div>
    </div>
</div>

<script>
// View adjustment details
function viewAdjustmentDetails(adjustmentId) {
    // Show loading
    document.getElementById('adjustmentDetailsContent').innerHTML = '<div class="text-center"><i class="fa fa-spinner fa-spin fa-2x"></i><p>Loading...</p></div>';
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('adjustmentDetailsModal'));
    modal.show();
    
    // Load details via AJAX
    fetch(`handlers/get_adjustment_details.php?adjustment_id=${adjustmentId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('adjustmentDetailsContent').innerHTML = data.html;
            } else {
                document.getElementById('adjustmentDetailsContent').innerHTML = 
                    `<div class="alert alert-danger">${data.message}</div>`;
            }
        })
        .catch(error => {
            document.getElementById('adjustmentDetailsContent').innerHTML = 
                `<div class="alert alert-danger">Error loading details: ${error.message}</div>`;
        });
}

// Print adjustment
function printAdjustment() {
    const printWindow = window.open('', '_blank');
    const content = document.getElementById('adjustmentDetailsContent').innerHTML;
    
    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>Stock Adjustment Details</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 20px; }
                table { width: 100%; border-collapse: collapse; margin: 20px 0; }
                th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                th { background-color: #f2f2f2; }
                .text-end { text-align: right; }
                .text-center { text-align: center; }
                .header { text-align: center; margin-bottom: 30px; }
                .summary { margin: 20px 0; padding: 15px; border: 1px solid #ddd; }
            </style>
        </head>
        <body>
            ${content}
        </body>
        </html>
    `);
    
    printWindow.document.close();
    printWindow.print();
}
</script>

<style>
.table th {
    background-color: #f8f9fa;
    border-color: #dee2e6;
}

.badge {
    font-size: 0.75em;
}

.text-end {
    text-align: right;
}

.text-center {
    text-align: center;
}

.pagination .page-link {
    color: #007bff;
}

.pagination .page-item.active .page-link {
    background-color: #007bff;
    border-color: #007bff;
}

.btn-group-sm .btn {
    padding: 0.25rem 0.5rem;
    font-size: 0.875rem;
}
</style>
