<?php include_once 'fungsi/fungsi.php'; ?>
<?php
if (isset($_POST['simpan_retur'])) {
    global $koneksi;
    $no_inv = mysqli_real_escape_string($koneksi, $_POST['no_inv']);
    $kdbarang = mysqli_real_escape_string($koneksi, $_POST['kdbarang']);
    $nm_barang = mysqli_real_escape_string($koneksi, $_POST['nm_barang']);
    $jumlah = (int)$_POST['jumlah'];
    $alasan = mysqli_real_escape_string($koneksi, $_POST['alasan']);
    $tanggal = date("Y-m-d");
    $jam = date("H:i:s");
    $kasir = $_SESSION['namakaskit'];
    
    // Generate no_retur
    $q = mysqli_query($koneksi, "SELECT MAX(id) as max_id FROM tb_retur");
    $r = mysqli_fetch_array($q);
    $next = ($r['max_id'] ? $r['max_id'] : 0) + 1;
    $no_retur = "RET/" . date('Ymd') . "/" . sprintf("%04s", $next);
    
    // Get harga from laporan_penjualan
    $qh = mysqli_query($koneksi, "SELECT total, jumlah_beli FROM laporan_penjualan WHERE no_inv='$no_inv' AND kdbarang='$kdbarang' LIMIT 1");
    $rh = mysqli_fetch_array($qh);
    $harga_satuan = $rh ? (int)($rh['total'] / max(1, $rh['jumlah_beli'])) : 0;
    $total_retur = $harga_satuan * $jumlah;
    
    // Insert retur
    $q_insert = mysqli_query($koneksi, "INSERT INTO tb_retur SET no_retur='$no_retur', no_inv='$no_inv', kdbarang='$kdbarang', nm_barang='$nm_barang', jumlah='$jumlah', harga='$harga_satuan', total='$total_retur', alasan='$alasan', tanggal='$tanggal', jam='$jam', kasir='$kasir'");
    
    // Restock
    mysqli_query($koneksi, "UPDATE tb_barang SET stok = stok + $jumlah WHERE kdbarang='$kdbarang'");
    
    // Log
    $log_msg = "Retur: $nm_barang x$jumlah (alasan: $alasan, No. $no_retur)";
    mysqli_query($koneksi, "INSERT INTO activity_log SET user_id='{$_SESSION['idkaskit']}', action='retur', detail='$log_msg', tanggal='$tanggal', jam='$jam'");
    
    if ($q_insert) {
        header("location: index.php?m=retur&s=title&msg=tambah_sukses");
    } else {
        header("location: index.php?m=retur&s=title&msg=gagal");
    }
    exit;
}
?>
<?php include 'comp/header.php'; ?>
<div class="content-wrapper">
  <div class="content-header">
    <div class="container-fluid">
      <div class="page-header">
        <div>
          <h1>Retur Barang</h1>
          <ul class="page-breadcrumb">
            <li><a href="index.php">Home</a></li>
            <li><span class="sep">›</span></li>
            <li>Retur Barang</li>
          </ul>
        </div>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modal-tambah-retur">
          <i class="fas fa-undo-alt"></i> Tambah Retur
        </button>
      </div>
    </div>
  </div>
  <section class="content">
    <div class="container-fluid">
      <div class="table-container">
        <div class="table-toolbar">
          <span class="table-toolbar-title"><i class="fas fa-undo-alt" style="margin-right:8px;color:var(--primary);"></i> Riwayat Retur</span>
          <form action="" method="GET" style="display:flex;gap:8px;align-items:center;">
            <input type="hidden" name="m" value="retur">
            <input type="hidden" name="s" value="title">
            <input type="text" name="cari" class="form-control form-control-sm" placeholder="Cari no. retur/invoice..." value="<?= isset($_GET['cari']) ? $_GET['cari'] : '' ?>" style="width:200px;border-radius:8px;">
            <button type="submit" name="go" class="btn btn-primary btn-sm" style="border-radius:8px;height:31px;display:inline-flex;align-items:center;"><i class="fas fa-search"></i></button>
            <?php if(isset($_GET['go']) && isset($_GET['cari'])): ?>
              <a href="?m=retur&s=title" class="btn btn-light btn-sm" style="border-radius:8px;border:1px solid var(--border);height:31px;display:inline-flex;align-items:center;">Reset</a>
            <?php endif; ?>
          </form>
        </div>
        <div class="table-responsive">
          <table class="table">
            <thead>
              <tr>
                <th>No</th>
                <th>No. Retur</th>
                <th>No. Invoice</th>
                <th>Barang</th>
                <th>Jumlah</th>
                <th>Total</th>
                <th>Alasan</th>
                <th>Tanggal</th>
                <th>Kasir</th>
              </tr>
            </thead>
            <tbody>
              <?php
              global $koneksi;
              $where = '';
              if (isset($_GET['go']) && !empty($_GET['cari'])) {
                  $cari = mysqli_real_escape_string($koneksi, $_GET['cari']);
                  $where = " WHERE no_retur LIKE '%$cari%' OR no_inv LIKE '%$cari%' OR nm_barang LIKE '%$cari%'";
              }
              $q = mysqli_query($koneksi, "SELECT * FROM tb_retur$where ORDER BY id DESC LIMIT 50");
              $i = 1;
              while ($r = mysqli_fetch_array($q)):
              ?>
              <tr>
                <td><?= $i++ ?></td>
                <td><code><?= $r['no_retur'] ?></code></td>
                <td><?= $r['no_inv'] ?></td>
                <td><strong><?= $r['nm_barang'] ?></strong></td>
                <td><?= $r['jumlah'] ?></td>
                <td>Rp <?= number_format($r['total'], 0, ',', '.') ?></td>
                <td><span style="font-size:0.8rem;color:var(--text-secondary)"><?= $r['alasan'] ?></span></td>
                <td><?= $r['tanggal'] ?></td>
                <td><?= $r['kasir'] ?></td>
              </tr>
              <?php endwhile; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </section>
</div>

<!-- Modal Tambah Retur -->
<div class="modal fade" id="modal-tambah-retur" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="fas fa-undo-alt" style="margin-right:8px;color:var(--primary);"></i> Tambah Retur Barang</h5>
        <button type="button" class="close" data-bs-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body">
        <form action="" method="POST" id="form-retur">
          <div class="form-group">
            <label>No. Invoice</label>
            <div class="input-group">
              <input type="text" class="form-control" name="no_inv" id="retur_no_inv" placeholder="Pilih invoice..." readonly required style="background:var(--surface-2);">
              <div class="input-group-append">
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modal_pilih_invoice" style="border-radius:0 8px 8px 0;">
                  <i class="fas fa-search"></i> Pilih
                </button>
              </div>
            </div>
          </div>
          <div class="form-group">
            <label>Kode Barang</label>
            <input type="text" class="form-control" name="kdbarang" id="retur_kdbarang" readonly required style="background:var(--surface-2);">
          </div>
          <div class="form-group">
            <label>Nama Barang</label>
            <input type="text" class="form-control" name="nm_barang" id="retur_nm_barang" readonly required style="background:var(--surface-2);">
          </div>
          <div class="form-group">
            <label>Jumlah Retur</label>
            <input type="number" class="form-control" name="jumlah" id="retur_jumlah" min="1" required>
            <small style="color:var(--text-muted);">Maksimal: <span id="retur_max_qty">0</span></small>
          </div>
          <div class="form-group">
            <label>Alasan Retur</label>
            <textarea class="form-control" name="alasan" rows="2" placeholder="Alasan pengembalian barang" required></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
        <button type="submit" form="form-retur" name="simpan_retur" class="btn btn-primary"><i class="fas fa-save"></i> Simpan</button>
      </div>
    </div>
  </div>
</div>

<!-- Modal Pilih Invoice -->
<div class="modal fade" id="modal_pilih_invoice" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="fas fa-file-invoice" style="margin-right:8px;color:var(--primary);"></i> Pilih Invoice</h5>
        <button type="button" class="close" data-bs-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body">
        <div style="margin-bottom:12px;">
          <input type="text" id="cari_invoice" class="form-control" placeholder="Cari no. invoice, nama barang..." onkeyup="filterInvoice(this.value)">
        </div>
        <div class="table-responsive" style="max-height:350px;overflow-y:auto;">
          <table class="table table-sm">
            <thead>
              <tr>
                <th>No. Invoice</th>
                <th>Barang</th>
                <th>Jumlah</th>
                <th>Total</th>
                <th>Tanggal</th>
                <th>Aksi</th>
              </tr>
            </thead>
            <tbody id="invoice_list">
              <?php
              global $koneksi;
              $q_inv = mysqli_query($koneksi, "SELECT no_inv FROM laporan_penjualan WHERE no_inv IS NOT NULL AND no_inv != '' GROUP BY no_inv ORDER BY MAX(id) DESC LIMIT 50");
              while ($inv = mysqli_fetch_array($q_inv)):
                $q_item = mysqli_query($koneksi, "SELECT * FROM laporan_penjualan WHERE no_inv='" . mysqli_real_escape_string($koneksi, $inv['no_inv']) . "' ORDER BY id ASC");
              ?>
              <tr class="invoice-group" data-no_inv="<?= $inv['no_inv'] ?>">
                <td colspan="6" style="background:var(--surface-2);font-weight:700;padding:6px 10px;font-size:0.82rem;">
                  <i class="fas fa-receipt"></i> <?= $inv['no_inv'] ?>
                </td>
              </tr>
              <?php while ($item = mysqli_fetch_array($q_item)): 
                  $q_retur_item = mysqli_query($koneksi, "SELECT SUM(jumlah) as jml_retur FROM tb_retur WHERE no_inv='" . mysqli_real_escape_string($koneksi, $inv['no_inv']) . "' AND kdbarang='" . mysqli_real_escape_string($koneksi, $item['kdbarang']) . "'");
                  $r_retur_item = mysqli_fetch_array($q_retur_item);
                  $jml_retur = (int)$r_retur_item['jml_retur'];
                  $sisa_bisa_retur = $item['jumlah_beli'] - $jml_retur;
              ?>
              <tr class="invoice-item" data-no_inv="<?= $inv['no_inv'] ?>" data-kdbarang="<?= $item['kdbarang'] ?>" data-nm_barang="<?= $item['nm_barang'] ?>" data-jumlah="<?= $sisa_bisa_retur ?>">
                <td></td>
                <td><strong><?= $item['nm_barang'] ?></strong> <code style="font-size:0.7rem;"><?= $item['kdbarang'] ?></code></td>
                <td>
                  <?= $item['jumlah_beli'] ?>
                  <?php if($jml_retur > 0): ?>
                    <br><small style="color:var(--danger);">-<?= $jml_retur ?> diretur</small>
                  <?php endif; ?>
                </td>
                <td>Rp <?= number_format($item['total'], 0, ',', '.') ?></td>
                <td><?= $item['tanggal'] ?></td>
                <td>
                  <?php if($sisa_bisa_retur > 0): ?>
                  <button class="btn btn-sm btn-primary" onclick="pilihRetur('<?= $inv['no_inv'] ?>', '<?= $item['kdbarang'] ?>', '<?= addslashes($item['nm_barang']) ?>', '<?= $sisa_bisa_retur ?>')">
                    Pilih
                  </button>
                  <?php else: ?>
                  <button class="btn btn-sm btn-secondary" disabled>Sudah Diretur</button>
                  <?php endif; ?>
                </td>
              </tr>
              <?php endwhile; ?>
              <?php endwhile; ?>
            </tbody>
          </table>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
      </div>
    </div>
  </div>
</div>

<script>
function pilihRetur(no_inv, kdbarang, nm_barang, max_qty) {
    document.getElementById('retur_no_inv').value = no_inv;
    document.getElementById('retur_kdbarang').value = kdbarang;
    document.getElementById('retur_nm_barang').value = nm_barang;
    document.getElementById('retur_max_qty').textContent = max_qty;
    document.getElementById('retur_jumlah').max = max_qty;
    var modalPicker = document.getElementById('modal_pilih_invoice');
    var modalRetur = document.getElementById('modal-tambah-retur');
    if (modalPicker) bootstrap.Modal.getInstance(modalPicker).hide();
    if (modalRetur) bootstrap.Modal.getOrCreateInstance(modalRetur).show();
}

function filterInvoice(keyword) {
    keyword = keyword.toLowerCase();
    document.querySelectorAll('.invoice-group, .invoice-item').forEach(function(el) {
        var text = el.textContent.toLowerCase();
        el.style.display = text.includes(keyword) ? '' : 'none';
    });
}
</script>

<?php if(isset($_GET['no_inv']) && !empty($_GET['no_inv'])): ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    var modalPicker = new bootstrap.Modal(document.getElementById('modal_pilih_invoice'));
    modalPicker.show();
    var inputCari = document.getElementById('cari_invoice');
    if (inputCari) {
        inputCari.value = '<?= htmlspecialchars($_GET['no_inv'], ENT_QUOTES) ?>';
        filterInvoice(inputCari.value);
    }
});
</script>
<?php endif; ?>

<?php include 'comp/footer.php'; ?>
