<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('product_management');

$pdo = getDB();

$products = $pdo->query("SELECT id, product_name, sku, current_stock, low_stock_qty FROM products WHERE status = 1 ORDER BY product_name")->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_id = (int)($_POST['product_id'] ?? 0);
    $adjustment_type = $_POST['adjustment_type'] ?? '';
    $quantity = (int)($_POST['quantity'] ?? 0);
    $reason = trim($_POST['reason'] ?? '');

    if (!$product_id || !$adjustment_type || $quantity <= 0) {
        $_SESSION['error'] = 'All fields are required and quantity must be greater than 0.';
    } else {
        // Get current stock
        $stmt = $pdo->prepare("SELECT current_stock, product_name FROM products WHERE id = ?");
        $stmt->execute([$product_id]);
        $product = $stmt->fetch();

        if (!$product) {
            $_SESSION['error'] = 'Product not found.';
        } else {
            $current = (int)$product['current_stock'];
            $movement_type = 'adjustment';
            $quantity_in = 0;
            $quantity_out = 0;

            if ($adjustment_type === 'Increase') {
                $quantity_in = $quantity;
                $new_balance = $current + $quantity;
                $note = 'Stock increased by ' . $quantity . ' - ' . $reason;
            } elseif ($adjustment_type === 'Decrease') {
                if ($quantity > $current) {
                    $_SESSION['error'] = 'Cannot decrease stock below 0. Current stock: ' . $current;
                    header('Location: stock_adjustment.php');
                    exit;
                }
                $quantity_out = $quantity;
                $new_balance = $current - $quantity;
                $note = 'Stock decreased by ' . $quantity . ' - ' . $reason;
            } elseif ($adjustment_type === 'Damaged') {
                if ($quantity > $current) {
                    $_SESSION['error'] = 'Cannot mark more items as damaged than current stock. Current stock: ' . $current;
                    header('Location: stock_adjustment.php');
                    exit;
                }
                $movement_type = 'damaged';
                $quantity_out = $quantity;
                $new_balance = $current - $quantity;
                $note = 'Marked as damaged: ' . $quantity . ' - ' . $reason;
            } else {
                $_SESSION['error'] = 'Invalid adjustment type.';
                header('Location: stock_adjustment.php');
                exit;
            }

            $result = createStockMovement($product_id, $movement_type, 'adjustment', null, $quantity_in, $quantity_out, $note, $_SESSION['user_id']);

            if ($result) {
                logActivity('Stock Adjustment', 'Products', $product_id, $note);
                $_SESSION['success'] = 'Stock adjustment completed successfully for ' . htmlspecialchars($product['product_name']) . '. New balance: ' . $new_balance;
            } else {
                $_SESSION['error'] = 'Stock adjustment failed. Please try again.';
            }
        }
    }
    header('Location: stock_adjustment.php');
    exit;
}

// Get recent adjustments
$stmt = $pdo->prepare("
    SELECT sm.*, p.product_name, p.sku, u.name as created_by_name
    FROM stock_movements sm
    JOIN products p ON sm.product_id = p.id
    LEFT JOIN users u ON sm.created_by = u.id
    WHERE sm.movement_type IN ('adjustment', 'damaged')
    ORDER BY sm.id DESC
    LIMIT 50
");
$stmt->execute();
$adjustments = $stmt->fetchAll();

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="page-title mb-0"><i class="fas fa-sliders-h me-2"></i>Stock Adjustment</h4>
            <a href="products.php" class="btn btn-secondary"><i class="fas fa-arrow-left me-1"></i>Back to Products</a>
        </div>

        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>
        <?php if (isset($_SESSION['error'])): ?><div class="alert alert-danger alert-dismissible"><?= $_SESSION['error']; unset($_SESSION['error']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <div class="row">
            <div class="col-md-5">
                <div class="card mb-3">
                    <div class="card-header"><i class="fas fa-edit me-2"></i>New Adjustment</div>
                    <div class="card-body">
                        <form method="POST">
                            <div class="mb-3">
                                <label class="form-label">Product *</label>
                                <select name="product_id" id="product_id" class="form-select select2" required>
                                    <option value="">Select Product</option>
                                    <?php foreach ($products as $p): ?>
                                    <option value="<?= $p['id'] ?>" data-stock="<?= (int)$p['current_stock'] ?>" data-low="<?= (int)$p['low_stock_qty'] ?>"><?= htmlspecialchars($p['product_name'] . ' (' . $p['sku'] . ')') ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Current Stock</label>
                                <div id="currentStockDisplay" class="form-control-plaintext fw-bold fs-5">-</div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Adjustment Type *</label>
                                <select name="adjustment_type" class="form-select" required>
                                    <option value="">Select Type</option>
                                    <option value="Increase">Increase Stock</option>
                                    <option value="Decrease">Decrease Stock</option>
                                    <option value="Damaged">Damaged / Write-off</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Quantity *</label>
                                <input type="number" name="quantity" class="form-control" min="1" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Reason / Note *</label>
                                <textarea name="reason" class="form-control" rows="3" placeholder="Explain why this adjustment is needed" required></textarea>
                            </div>
                            <button type="submit" class="btn btn-primary"><i class="fas fa-save me-1"></i>Process Adjustment</button>
                        </form>
                    </div>
                </div>
            </div>

            <div class="col-md-7">
                <div class="card">
                    <div class="card-header"><i class="fas fa-list me-2"></i>Recent Stock Adjustments</div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="adjustmentsTable" class="table table-hover datatable">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Product</th>
                                        <th>Type</th>
                                        <th>In</th>
                                        <th>Out</th>
                                        <th>Balance</th>
                                        <th>Note</th>
                                        <th>By</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (!empty($adjustments)): ?>
                                    <?php foreach ($adjustments as $a): ?>
                                    <tr>
                                        <td><?= formatDateTime($a['created_at']) ?></td>
                                        <td><?= htmlspecialchars($a['product_name']) ?></td>
                                        <td>
                                            <?php
                                            $adj_class = $a['movement_type'] == 'damaged' ? 'bg-danger' : ($a['quantity_in'] > 0 ? 'bg-success' : 'bg-warning');
                                            $adj_label = $a['movement_type'] == 'damaged' ? 'Damaged' : ($a['quantity_in'] > 0 ? 'Increase' : 'Decrease');
                                            ?>
                                            <span class="badge <?= $adj_class ?>"><?= $adj_label ?></span>
                                        </td>
                                        <td><?= $a['quantity_in'] ?: '-' ?></td>
                                        <td><?= $a['quantity_out'] ?: '-' ?></td>
                                        <td><?= (int)$a['balance_after'] ?></td>
                                        <td><?= htmlspecialchars($a['note'] ?? '-') ?></td>
                                        <td><?= htmlspecialchars($a['created_by_name'] ?? '-') ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    $('#product_id').on('change', function() {
        var selected = $(this).find('option:selected');
        var stock = selected.data('stock');
        if (stock !== undefined) {
            $('#currentStockDisplay').text(stock);
        } else {
            $('#currentStockDisplay').text('-');
        }
    });
});
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
