<?php
require_once '../../includes/auth_middleware.php';
require_once '../../config/database.php';
require_once '../../includes/header.php';

// Proteksi halaman: Staff & Admin
checkRole(['staff', 'admin']);

try {
    // 1. Ambil data menu produk
    $stmt = $pdo->query("SELECT id, product_name, selling_price FROM products ORDER BY product_name ASC");
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 2. Ambil 5 transaksi terakhir (Perbaikan: Tambah pemanggilan kolom discount_amount)
    $hist_stmt = $pdo->prepare("
        SELECT id, total_omzet, discount_amount, transaction_date 
        FROM transactions 
        WHERE user_id = ? AND DATE(transaction_date) = CURDATE() 
        ORDER BY transaction_date DESC LIMIT 5
    ");
    $hist_stmt->execute([$_SESSION['user_id']]);
    $recent_history = $hist_stmt->fetchAll();

    // 3. CEK STATUS ABSEN HARI INI (Fitur Baru)
    $absen_stmt = $pdo->prepare("SELECT type FROM attendance WHERE user_id = ? AND DATE(attendance_time) = CURDATE() ORDER BY attendance_time DESC LIMIT 1");
    $absen_stmt->execute([$_SESSION['user_id']]);
    $status_absen = $absen_stmt->fetch();

    $text_absen = "📸 Kamera Absen";
    $warna_absen = "#3b82f6"; // Biru default

    if (!$status_absen) {
        $text_absen = "👋 Wajib Absen Masuk";
        $warna_absen = "#f59e0b"; // Orange
    } elseif ($status_absen['type'] == 'in') {
        $text_absen = "🚪 Akhiri Shift (Pulang)";
        $warna_absen = "#ef4444"; // Merah
    } else {
        $text_absen = "✅ Shift Selesai";
        $warna_absen = "#9ca3af"; // Abu-abu
    }

} catch (PDOException $e) {
    die("Error mengambil data: " . $e->getMessage());
}
?>

<div class="container" style="padding-bottom: 120px; max-width: 800px;">
    
    <header style="margin-bottom: 2rem; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;">
        <div>
            <h2 style="margin:0;">INPUT JUALAN</h2>
            <p style="color: #6b7280; margin:0;">Kasir: <?= htmlspecialchars($_SESSION['username']) ?></p>
        </div>
        
        <a href="attendance.php" style="background: <?= $warna_absen ?>; color: white; text-decoration: none; padding: 10px 20px; border-radius: 8px; font-weight: bold; box-shadow: 0 4px 6px rgba(0,0,0,0.1); display: flex; align-items: center; gap: 5px; transition: 0.2s;">
            <?= $text_absen ?>
        </a>
    </header>

    <?php if (!$status_absen): ?>
        <div style="background: #fffbeb; border-left: 5px solid #f59e0b; color: #b45309; padding: 15px; margin-bottom: 20px; border-radius: 8px;">
            ⚠️ <strong>Halo!</strong> Jangan lupa <b>Absen Masuk</b> dulu ya sebelum mulai melayani pembeli.
        </div>
    <?php endif; ?>

    <?php if (isset($_GET['status']) && $_GET['status'] == 'success'): ?>
        <div class="card" style="background: #ecfdf5; border-left: 5px solid #10b981; color: #065f46; padding: 15px; margin-bottom: 20px;">
            ✅ Transaksi berhasil disimpan! Stok otomatis terpotong.
        </div>
    <?php endif; ?>

    <form action="../../api/submit_production.php" method="POST">
        <?php if (count($products) > 0): ?>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 10px;">
                <?php foreach ($products as $p): ?>
                    <div class="card" style="margin-bottom: 0;">
                        <div style="display: flex; justify-content: space-between; font-weight: bold; margin-bottom: 10px;">
                            <span><?= htmlspecialchars($p['product_name']) ?></span>
                            <span style="color: var(--accent);">Rp <?= number_format($p['selling_price'], 0, ',', '.') ?></span>
                        </div>
                        
                        <div class="stepper" style="display: flex; align-items: center; gap: 1rem;">
                            <button type="button" onclick="changeVal('prod_<?= $p['id'] ?>', -1)"
                                    style="width: 45px; height: 45px; border-radius: 8px; border: none; font-size: 1.5rem; font-weight: bold; cursor: pointer; background-color: #e5e7eb;">-</button>
                            
                            <input type="number" name="products[<?= $p['id'] ?>]" id="prod_<?= $p['id'] ?>" 
                                   value="0" readonly 
                                   style="text-align: center; border: none; font-size: 1.5rem; font-weight: 800; flex: 1; background: transparent;">
                            
                            <button type="button" onclick="changeVal('prod_<?= $p['id'] ?>', 1)"
                                    style="width: 45px; height: 45px; border-radius: 8px; border: none; font-size: 1.5rem; font-weight: bold; cursor: pointer; background-color: var(--primary); color: var(--accent);">+</button>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="card" style="text-align: center; color: #6b7280;">
                Belum ada produk yang didaftarkan.
            </div>
        <?php endif; ?>

        <div class="card" style="border: 2px dashed #fbbf24; background: #fffbeb; margin-top: 1.5rem;">
            <label style="font-weight: bold; color: #b45309; display: block; margin-bottom: 10px;">🎁 POTONGAN DISKON / PROMO</label>
            <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                <select name="discount_type" id="discount_type" onchange="toggleDiscount()" style="padding: 12px; border-radius: 8px; border: 1px solid #fde68a; outline: none; flex: 1; font-weight: bold; color: #78350f;">
                    <option value="none">Tanpa Diskon</option>
                    <option value="nominal">Nominal Rupiah (Rp)</option>
                    <option value="percentage">Persentase (%)</option>
                </select>
                <input type="number" name="discount_value" id="discount_value" value="0" min="0" step="0.01" style="padding: 12px; border-radius: 8px; border: 1px solid #fde68a; outline: none; flex: 1; display: none; font-weight: bold;" placeholder="Masukkan nilai...">
            </div>
        </div>

        <div style="position: fixed; bottom: 0; left: 0; right: 0; padding: 1rem; background: white; border-top: 1px solid #eee; z-index: 100; box-shadow: 0 -4px 10px rgba(0,0,0,0.05);">
            <div style="max-width: 800px; margin: 0 auto;">
                <button type="submit" class="btn-primary" style="width: 100%; font-size: 1.1rem; padding: 15px;">SIMPAN TRANSAKSI & CETAK NOTA</button>
            </div>
        </div>
    </form>

    <div class="card" style="margin-top: 1.5rem; border-top: 5px solid #3b82f6;">
        <label style="font-weight: bold; color: #1d4ed8; display: block; margin-bottom: 10px;">🕒 RIWAYAT TRANSAKSI KAMU HARI INI</label>
        <table style="width: 100%; border-collapse: collapse; font-size: 0.9rem;">
            <tbody>
                <?php if(count($recent_history) > 0): ?>
                    <?php foreach($recent_history as $hist): 
                        // Perhitungan: Omzet Kotor dikurangi Diskon untuk dapat Total Bayar Aktual
                        $total_bayar_aktual = $hist['total_omzet'] - $hist['discount_amount'];
                    ?>
                    <tr style="border-bottom: 1px solid #eee;">
                        <td style="padding: 12px 0;">
                            <div style="font-weight: bold; color: #374151;">#TRX-<?= str_pad($hist['id'], 5, '0', STR_PAD_LEFT) ?></div>
                            <div style="color: #6b7280; font-size: 0.8rem;"><?= date('H:i', strtotime($hist['transaction_date'])) ?> WIB</div>
                        </td>
                        <td style="padding: 12px 0; text-align: right;">
                            <div style="font-weight: 900; color: #10B981; font-size: 1rem;">
                                Rp <?= number_format($total_bayar_aktual, 0, ',', '.') ?>
                            </div>
                            <?php if($hist['discount_amount'] > 0): ?>
                                <div style="font-size: 0.75rem; color: #dc2626; font-weight: bold;">
                                    (Disc: -Rp <?= number_format($hist['discount_amount'], 0, ',', '.') ?>)
                                </div>
                            <?php endif; ?>
                        </td>
                        <td style="padding: 12px 0; text-align: right; width: 80px;">
                            <button type="button" onclick="reprintNota(<?= $hist['id'] ?>)" style="background: #e5e7eb; color: #374151; border: 1px solid #d1d5db; padding: 6px 12px; border-radius: 6px; cursor: pointer; font-weight: bold; transition: 0.2s;" onmouseover="this.style.background='#d1d5db'" onmouseout="this.style.background='#e5e7eb'">
                                🖨️ Cetak
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr><td colspan="3" style="text-align: center; color: #9ca3af; padding: 20px;">Belum ada penjualan darimu hari ini.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

</div>

<script>
function changeVal(id, delta) {
    const input = document.getElementById(id);
    let newVal = parseInt(input.value) + delta;
    input.value = newVal < 0 ? 0 : newVal;
}

function toggleDiscount() {
    const type = document.getElementById('discount_type').value;
    const input = document.getElementById('discount_value');
    
    if (type === 'none') {
        input.style.display = 'none';
        input.value = 0;
    } else {
        input.style.display = 'block';
        input.placeholder = type === 'percentage' ? 'Contoh: 10 (Untuk Diskon 10%)' : 'Contoh: 5000 (Untuk Diskon Rp 5.000)';
    }
}

function reprintNota(id) {
    window.open('print_receipt.php?id=' + id, 'Nota', 'width=400,height=600');
}

// Fitur Auto-Print saat baru selesai disimpan
<?php if (isset($_GET['print_id']) && is_numeric($_GET['print_id'])): ?>
    window.open('print_receipt.php?id=<?= $_GET['print_id'] ?>', 'Nota', 'width=400,height=600');
    window.history.replaceState({}, document.title, "production_input.php");
<?php endif; ?>
</script>

</body>
</html>