<?php
session_start();
require_once __DIR__.'/config/config.php';
if(!isset($_SESSION['login'])) die("Akses ditolak");

$role = $_SESSION['role'];
$npsn_login = $_SESSION['npsn'] ?? '';

/* ================= FILTER ================= */
$bulan_req = $_GET['bulan'] ?? date('Y-m');
[$tahun,$bulan] = explode('-',$bulan_req);
$bulan = (int)$bulan;

$npsn = $_GET['npsn'] ?? ($role!='admin' ? $npsn_login : '');

/* ================= BULAN SEBELUMNYA ================= */
$prev_bulan = $bulan-1;
$prev_tahun = $tahun;
if($prev_bulan==0){
    $prev_bulan=12;
    $prev_tahun--;
}

/* ================= HEADER OPNAME ================= */
$q = mysqli_query($conn,"
SELECT id_opname,locked 
FROM stok_opname
WHERE npsn='$npsn' 
  AND bulan='$bulan' 
  AND tahun='$tahun'
LIMIT 1
");

if($q && mysqli_num_rows($q)>0){
    $r = mysqli_fetch_assoc($q);
    $id_opname = $r['id_opname'];
    $locked    = (int)$r['locked'];
}else{
    mysqli_query($conn,"
        INSERT INTO stok_opname(npsn,bulan,tahun,tgl_opname,locked)
        VALUES('$npsn','$bulan','$tahun',CURDATE(),0)
    ");
    $id_opname = mysqli_insert_id($conn);
    $locked = 0;
}

/* ================= SIMPAN ================= */
if(isset($_POST['simpan'])){
    foreach($_POST['kode'] as $i=>$kode){

        $aq = (float)$_POST['awal_qty'][$i];
        $aj = (float)$_POST['awal_jumlah'][$i];
        $mq = (float)$_POST['masuk_qty'][$i];
        $mj = (float)$_POST['masuk_jumlah'][$i];
        $kq = (float)$_POST['keluar_qty'][$i];
        $kj = (float)$_POST['keluar_jumlah'][$i];

        $akhir_qty    = (float)$_POST['akhir_qty'][$i];
        $akhir_jumlah = (float)$_POST['akhir_jumlah'][$i];
        $akhir_harga  = ($akhir_qty > 0) ? ($akhir_jumlah / $akhir_qty) : 0;

        mysqli_query($conn,"
            INSERT INTO stok_opname_detail
            (id_opname,kode_rekening,nama_barang,satuan,
             awal_qty,awal_jumlah,masuk_qty,masuk_jumlah,
             keluar_qty,keluar_jumlah,
             akhir_qty,akhir_harga,akhir_jumlah)
            VALUES
            ('$id_opname','$kode','{$_POST['nama'][$i]}','{$_POST['satuan'][$i]}',
             '$aq','$aj','$mq','$mj','$kq','$kj',
             '$akhir_qty','$akhir_harga','$akhir_jumlah')
            ON DUPLICATE KEY UPDATE
             keluar_qty='$kq',
             keluar_jumlah='$kj',
             akhir_qty='$akhir_qty',
             akhir_harga='$akhir_harga',
             akhir_jumlah='$akhir_jumlah'
        ");
    }

    // ❗ JANGAN LOCK DI SINI
    // locked tetap 0 supaya masih bisa edit
}

/* ================= DATA DETAIL ================= */
$sql="
SELECT
 rm.kode_rekening AS kode_induk,
 rm.nama_rekening AS nama_induk,
 k.kode_rekening,
 k.uraian,
 k.satuanb,

 COALESCE(prev.akhir_qty,0) AS awal_qty,
 COALESCE(prev.akhir_jumlah,0) AS awal_jumlah,

 CASE 
   WHEN so.locked=0 THEN SUM(k.jumb)
   ELSE COALESCE(cur.masuk_qty,0)
 END AS masuk_qty,

 CASE 
   WHEN so.locked=0 THEN SUM(k.pengeluaran)
   ELSE COALESCE(cur.masuk_jumlah,0)
 END AS masuk_jumlah,

 COALESCE(cur.keluar_qty,0) AS keluar_qty,
 COALESCE(cur.keluar_jumlah,0) AS keluar_jumlah

FROM kwitansi k
JOIN rekening_map rm ON rm.kode_rekening=k.kode_rekening
JOIN stok_opname so ON so.id_opname='$id_opname'

LEFT JOIN stok_opname so_prev
 ON so_prev.npsn='$npsn'
 AND so_prev.bulan='$prev_bulan'
 AND so_prev.tahun='$prev_tahun'

LEFT JOIN stok_opname_detail prev
 ON prev.id_opname=so_prev.id_opname
 AND prev.kode_rekening=k.kode_rekening

LEFT JOIN stok_opname_detail cur
 ON cur.id_opname='$id_opname'
 AND cur.kode_rekening=k.kode_rekening

WHERE k.npsn='$npsn'
 AND MONTH(k.tanggal)='$bulan'
 AND YEAR(k.tanggal)='$tahun'

GROUP BY k.kode_rekening
ORDER BY rm.kode_rekening,k.uraian
";

$q_detail = mysqli_query($conn,$sql);

/* ================= KELOMPOK ================= */
$data=[];
while($r=mysqli_fetch_assoc($q_detail)){
    $data[$r['kode_induk']]['nama']=$r['nama_induk'];
    $data[$r['kode_induk']]['item'][]=$r;
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Stok Opname</title>
<link rel="icon" href="assets/images/logomu.ico">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
.table{font-size:12px;white-space:nowrap}
.bg-induk{background:#f1f1f1;font-weight:bold}
body{
    font-size:13px;
}

.card{
    border-radius:12px;
}

.table{
    font-size:12px;
    white-space:nowrap;
}

thead th{
    vertical-align:middle;
    text-align:center;
    background:#eef2f7;
}

.table thead{
    position:sticky;
    top:0;
    z-index:2;
}

.bg-induk{
    background:#e7f1ff !important;
    font-weight:600;
    color:#0d47a1;
}

td{
    vertical-align:middle;
}

td.text-end{
    font-family: Consolas, monospace;
}

input.form-control-sm{
    min-width:90px;
    text-align:right;
}

.badge-rek{
    background:#0d6efd;
    font-size:11px;
}

tfoot td{
    background:#f8f9fa;
    font-weight:bold;
}

.btn{
    border-radius:8px;
}

.header-title{
    font-weight:600;
    letter-spacing:0.5px;
}
</style>
</head>
<body class="bg-light">
<div class="container-fluid mt-3">
<div class="card shadow-sm">
<div class="card-body">
<div class="d-flex justify-content-between align-items-center mb-3">
    <div>
        <h5 class="header-title mb-0">📦 STOK OPNAME PERSEDIAAN</h5>
        <small class="text-muted">
            Bulan <?= date('F', mktime(0,0,0,$bulan,1)) ?> <?= $tahun ?>
        </small>
    </div>
    <span class="badge bg-primary">
        <?= $role=='admin'?'ADMIN':'SEKOLAH' ?>
    </span>
</div>
<a href="dashboard.php" class="btn btn-outline-secondary btn-sm">
    ⬅️ Kembali ke Dashboard
</a>
<hr class="mt-2 mb-3">


<!-- FILTER -->
<form class="row g-2 mb-2">
<?php if($role=='admin'): ?>
<div class="col-md-4">
<select name="npsn" class="form-select form-select-sm">
<?php
$q=mysqli_query($conn,"SELECT npsn,nama_sekolah FROM sekolah");
while($s=mysqli_fetch_assoc($q)):
?>
<option value="<?= $s['npsn'] ?>" <?= $s['npsn']==$npsn?'selected':'' ?>>
<?= $s['nama_sekolah'] ?>
</option>
<?php endwhile; ?>
</select>
</div>
<?php endif; ?>
<div class="col-md-3">
<input type="month" name="bulan" value="<?= "$tahun-".str_pad($bulan,2,'0',STR_PAD_LEFT) ?>" class="form-control form-control-sm">
</div>
<div class="col-md-2">
<button class="btn btn-primary btn-sm">Tampilkan</button>
</div>
</form>

<form method="post">
<table class="table table-bordered table-sm">
<thead class="table-secondary text-center">
<tr>
<th rowspan="2">No</th>
<th rowspan="2">Uraian</th>
<th colspan="3">Saldo Awal</th>
<th colspan="2">Masuk</th>
<th colspan="2">Digunakan</th>
<th colspan="3">Saldo Akhir</th>
<th rowspan="2">Aksi</th>
</tr>
<tr>
<th>Qty</th><th>Jumlah</th><th></th>
<th>Qty</th><th>Jumlah</th>
<th>Qty</th><th>Jumlah</th>
<th>Qty</th><th>Harga</th><th>Jumlah</th>
</tr>
</thead>
<tbody>
<?php
$no=1;
foreach($data as $kode=>$g):
?>
<tr class="bg-induk">
<td colspan="11">
<span class="badge badge-rek me-2"><?= $kode ?></span>
<?= $g['nama'] ?>
</td>
</tr>
<?php foreach($g['item'] as $d):
$aq=$d['awal_qty']; $aj=$d['awal_jumlah'];
$mq=$d['masuk_qty']; $mj=$d['masuk_jumlah'];
$kq=$d['keluar_qty']; $kj=$d['keluar_jumlah'];
$akhir_qty=$aq+$mq-$kq;
$akhir_jumlah=$aj+$mj-$kj;
$akhir_harga=$akhir_qty>0?($akhir_jumlah/$akhir_qty):0;
$locked = file_exists("pdf/stokopname_{$npsn}_{$bulan}_{$tahun}.pdf");

?>
<tr>
<td><?= $no++ ?></td>
<td><?= $d['uraian'] ?></td>

<td><?= $aq ?></td>
<td class="text-end"><?= number_format($aj,0,',','.') ?></td>
<td></td>

<td><?= $mq ?></td>
<td class="text-end"><?= number_format($mj,0,',','.') ?></td>

<td>
<input type="number"
name="keluar_qty[]"
value="<?= $kq ?>"
class="form-control form-control-sm text-end keluar-qty"
readonly>
</td>

<td>
<input type="number"
name="keluar_jumlah[]"
value="<?= $kj ?>"
class="form-control form-control-sm text-end keluar-jumlah"
readonly>
</td>

<td class="akhir-qty"><?= $akhir_qty ?></td>
<td class="text-end akhir-harga"><?= number_format($akhir_harga,0,',','.') ?></td>
<td class="text-end akhir-jumlah"><?= number_format($akhir_jumlah,0,',','.') ?></td>

<!-- ✅ AKSI EDIT -->
<td class="text-center">
    <?php if(!$locked): ?>
<button type="button" class="btn btn-warning btn-sm btn-edit">✏️</button>
<?php else: ?>
<span class="text-muted">🔒</span>
<?php endif; ?>
</td>

<input type="hidden" name="kode[]" value="<?= $d['kode_rekening'] ?>">
<input type="hidden" name="nama[]" value="<?= $d['uraian'] ?>">
<input type="hidden" name="satuan[]" value="<?= $d['satuanb'] ?>">
<input type="hidden" name="awal_qty[]" value="<?= $aq ?>">
<input type="hidden" class="awal-qty" value="<?= $aq ?>">
<input type="hidden" name="awal_jumlah[]" value="<?= $aj ?>">
<input type="hidden" class="awal-jumlah" value="<?= $aj ?>">
<input type="hidden" name="masuk_qty[]" value="<?= $mq ?>">
<input type="hidden" class="masuk-qty" value="<?= $mq ?>">
<input type="hidden" name="masuk_jumlah[]" value="<?= $mj ?>">
<input type="hidden" class="masuk-jumlah" value="<?= $mj ?>">
<input type="hidden" name="akhir_qty[]" class="h-akhir-qty" value="<?= $akhir_qty ?>">
<input type="hidden" name="akhir_jumlah[]" class="h-akhir-jumlah" value="<?= $akhir_jumlah ?>">

</tr>
<?php endforeach; endforeach; ?>
</tbody>
</table>
<div class="d-flex justify-content-between align-items-center mt-3">

  <!-- TOMBOL SIMPAN -->
  <button name="simpan" class="btn btn-success btn-sm px-4">
    💾 Simpan Stok Opname
  </button>

  <!-- TOMBOL CETAK -->
  <?php
  $bulan_param = $bulan.'-'.$tahun;
  $npsn_param  = ($role === 'admin') ? ($npsn_filter ?? '') : $npsn_login;
  ?>
  <a href="cetak_stokopnamepdf.php?bulan=<?= $bulan_param ?>&npsn=<?= $npsn_param ?>"
     target="_blank"
     class="btn btn-danger btn-sm px-4">
     🖨️ Cetak PDF
  </a>

</div>
</form>
</div>
</div>
</div>
</div>
<script>
document.querySelectorAll('.btn-edit').forEach(btn => {
  btn.addEventListener('click', function(){

    const row = this.closest('tr');

    const awalQty = parseFloat(row.querySelector('.awal-qty').value);
    const awalJml = parseFloat(row.querySelector('.awal-jumlah').value);
    const masukQty = parseFloat(row.querySelector('.masuk-qty').value);
    const masukJml = parseFloat(row.querySelector('.masuk-jumlah').value);

    const keluarQty = row.querySelector('.keluar-qty');
    const keluarJml = row.querySelector('.keluar-jumlah');

    const akhirQtyEl = row.querySelector('.akhir-qty');
    const akhirHargaEl = row.querySelector('.akhir-harga');
    const akhirJumlahEl = row.querySelector('.akhir-jumlah');

    const hAkhirQty = row.querySelector('.h-akhir-qty');
    const hAkhirJumlah = row.querySelector('.h-akhir-jumlah');

    // ===== MODE EDIT =====
    if (keluarQty.hasAttribute('readonly')) {
        keluarQty.removeAttribute('readonly');
        keluarJml.removeAttribute('readonly');
        keluarQty.focus();

        this.innerHTML = '💾';
        this.classList.replace('btn-warning','btn-success');
        return;
    }

    // ===== MODE SIMPAN =====
    let kq = parseFloat(keluarQty.value) || 0;
    let kj = parseFloat(keluarJml.value) || 0;

    let stokTersedia = awalQty + masukQty;

    // VALIDASI
    if (kq > stokTersedia) {
        alert('Qty digunakan melebihi stok tersedia!');
        keluarQty.focus();
        return;
    }

    // HITUNG
    let akhirQty = stokTersedia - kq;
    let akhirJumlah = (awalJml + masukJml) - kj;
    let akhirHarga = akhirQty > 0 ? akhirJumlah / akhirQty : 0;

    // TAMPILKAN KE TABEL
    akhirQtyEl.innerText = akhirQty;
    akhirHargaEl.innerText = Math.round(akhirHarga).toLocaleString('id-ID');
    akhirJumlahEl.innerText = Math.round(akhirJumlah).toLocaleString('id-ID');

    // 🔑 SIMPAN KE HIDDEN (INI KUNCI UTAMA)
    hAkhirQty.value = akhirQty;
    hAkhirJumlah.value = akhirJumlah;

    // KUNCI KEMBALI
    keluarQty.setAttribute('readonly',true);
    keluarJml.setAttribute('readonly',true);

    this.innerHTML = '✏️';
    this.classList.replace('btn-success','btn-warning');
  });
});
</script>

</body>
</html>
