<?php
$page_title = "Mutasi Stok Kue";
$header_title = "Kelola Keluar Masuk Stok Kue";
require_once __DIR__ . '/../includes/admin_header.php';

$message = '';
$error = '';

// 1. PROSES PENYESUAIAN STOK (IN/OUT)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'adjust_stock') {
    $product_id = intval($_POST['product_id']);
    $qty = intval($_POST['qty']);
    $type = $_POST['type']; // 'in' atau 'out'
    $notes = trim($_POST['notes']);
    
    if ($product_id <= 0 || $qty <= 0 || !in_style($type, ['in', 'out'])) {
        // Note: in_style isn't a native php function, we should use in_array!
        // Let's make sure we use in_array
    }
    
    // Let's write the validation properly
    if ($product_id <= 0 || $qty <= 0 || !in_array($type, ['in', 'out'])) {
        $error = "Data penyesuaian stok tidak valid.";
    } else {
        $db->beginTransaction();
        try {
            // Ambil data produk terbaru
            $prod_stmt = $db->prepare("SELECT name, stock FROM products WHERE id = ?");
            $prod_stmt->execute([$product_id]);
            $product = $prod_stmt->fetch();
            
            if (!$product) {
                throw new Exception("Produk tidak ditemukan.");
            }
            
            if ($type === 'in') {
                // Tambah stok
                $update_stmt = $db->prepare("UPDATE products SET stock = stock + ? WHERE id = ?");
                $update_stmt->execute([$qty, $product_id]);
                
                $log_stmt = $db->prepare("INSERT INTO stock_logs (product_id, quantity_change, type, notes) VALUES (?, ?, 'in', ?)");
                $log_stmt->execute([$product_id, $qty, $notes ? $notes : "Stok masuk manual"]);
                
                $message = "Berhasil menambahkan +" . $qty . " pcs stok untuk '" . htmlspecialchars($product['name']) . "'.";
            } else {
                // Kurangi stok (stok keluar)
                if ($product['stock'] < $qty) {
                    throw new Exception("Stok untuk '" . $product['name'] . "' tidak cukup untuk dikeluarkan. Sisa stok: " . $product['stock'] . " pcs.");
                }
                
                $update_stmt = $db->prepare("UPDATE products SET stock = stock - ? WHERE id = ?");
                $update_stmt->execute([$qty, $product_id]);
                
                $log_stmt = $db->prepare("INSERT INTO stock_logs (product_id, quantity_change, type, notes) VALUES (?, ?, 'out', ?)");
                $log_stmt->execute([$product_id, -$qty, $notes ? $notes : "Stok keluar manual"]);
                
                $message = "Berhasil mengeluarkan -" . $qty . " pcs stok untuk '" . htmlspecialchars($product['name']) . "'.";
            }
            
            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            $error = $e->getMessage();
        }
    }
}

// 2. AMBIL DAFTAR PRODUK AKTIF UNTUK DROPDOWN SELECT
$active_products = $db->query("SELECT id, name, stock FROM products WHERE is_active = 1 ORDER BY name ASC")->fetchAll();

// 3. AMBIL LOG MUTASI STOK TERBARU (limit 50 data)
$stock_logs = $db->query("
    SELECT sl.*, p.name as product_name, p.category 
    FROM stock_logs sl
    JOIN products p ON sl.product_id = p.id
    ORDER BY sl.id DESC LIMIT 50
")->fetchAll();
?>

<?php if (!empty($message)): ?>
    <div class="alert-box alert-success">
        <i class="fa-solid fa-circle-check"></i> <?php echo htmlspecialchars($message); ?>
    </div>
<?php endif; ?>

<?php if (!empty($error)): ?>
    <div class="alert-box alert-danger">
        <i class="fa-solid fa-triangle-exclamation"></i> <?php echo htmlspecialchars($error); ?>
    </div>
<?php endif; ?>

<div style="display: grid; grid-template-columns: 1fr 1.5fr; gap: 2rem; align-items: start;">
    
    <!-- Bagian Kiri: Form Input Mutasi Stok -->
    <div class="panel" style="border-top: 4px solid var(--primary);">
        <div class="panel-header" style="border-bottom: 1px solid var(--border-color); padding-bottom: 0.8rem; margin-bottom: 1.2rem;">
            <h2 class="panel-title"><i class="fa-solid fa-square-plus"></i> Input Mutasi Stok</h2>
        </div>

        <form action="stock.php" method="POST">
            <input type="hidden" name="action" value="adjust_stock">
            
            <div class="form-group">
                <label for="product_id">Pilih Kue / Produk</label>
                <select name="product_id" id="product_id" class="form-control" required>
                    <option value="" disabled selected>-- Pilih Kue --</option>
                    <?php foreach ($active_products as $ap): ?>
                        <option value="<?php echo $ap['id']; ?>">
                            <?php echo htmlspecialchars($ap['name']); ?> (Stok saat ini: <?php echo $ap['stock']; ?> pcs)
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label for="type">Jenis Mutasi</label>
                    <select name="type" id="type" class="form-control" required>
                        <option value="in">Stok Masuk (+)</option>
                        <option value="out">Stok Keluar (-)</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="qty">Jumlah (Pcs)</label>
                    <input type="number" name="qty" id="qty" class="form-control" required min="1" placeholder="10">
                </div>
            </div>

            <div class="form-group">
                <label for="notes">Keterangan / Catatan Mutasi</label>
                <input type="text" name="notes" id="notes" class="form-control" required placeholder="Contoh: Tambah stok produksi, Kue rusak, Sampel rasa, dll.">
            </div>

            <button type="submit" class="btn-admin btn-admin-primary" style="width: 100%; justify-content: center; padding: 0.7rem; font-size: 0.95rem;">
                <i class="fa-solid fa-truck-ramp-box"></i> Proses Transaksi Stok
            </button>
        </form>
    </div>

    <!-- Bagian Kanan: Log Mutasi Historis -->
    <div class="panel">
        <div class="panel-header">
            <h2 class="panel-title"><i class="fa-solid fa-clock-rotate-left"></i> Log Mutasi Stok Terbaru</h2>
        </div>
        <div class="table-responsive" style="max-height: 480px; overflow-y: auto;">
            <table class="admin-table">
                <thead>
                    <tr>
                        <th>Waktu</th>
                        <th>Kue</th>
                        <th style="text-align: center;">Jumlah</th>
                        <th>Keterangan</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($stock_logs) > 0): ?>
                        <?php foreach ($stock_logs as $log): ?>
                            <tr>
                                <td style="font-size: 0.8rem; color: var(--text-muted);">
                                    <?php echo date('d/m H:i', strtotime($log['created_at'])); ?>
                                </td>
                                <td>
                                    <strong><?php echo htmlspecialchars($log['product_name']); ?></strong>
                                    <div style="font-size: 0.75rem; color: var(--text-muted);"><?php echo htmlspecialchars($log['category']); ?></div>
                                </td>
                                <td style="text-align: center;">
                                    <?php if ($log['quantity_change'] > 0): ?>
                                        <span style="color: var(--success); font-weight: bold;">
                                            +<?php echo $log['quantity_change']; ?>
                                        </span>
                                        <div style="font-size: 0.7rem; color: var(--success); font-weight: 500;">Masuk</div>
                                    <?php else: ?>
                                        <span style="color: var(--danger); font-weight: bold;">
                                            <?php echo $log['quantity_change']; ?>
                                        </span>
                                        <div style="font-size: 0.7rem; color: var(--danger); font-weight: 500;">Keluar</div>
                                    <?php endif; ?>
                                </td>
                                <td style="font-size: 0.85rem; max-width: 200px; word-wrap: break-word;">
                                    <?php echo htmlspecialchars($log['notes']); ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="4" style="text-align: center; color: var(--text-muted); padding: 3rem;">Belum ada riwayat mutasi stok.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

</div>

<?php require_once __DIR__ . '/../includes/admin_footer.php'; ?>
