<?php
require_once __DIR__.'/../includes/db.php';
require_once __DIR__.'/../includes/auth.php';

$id = (int)($_GET['id'] ?? 0);
$p = $mysqli->query("
  SELECT * FROM pengajuan_surat_pengantar_kayu WHERE id=$id
")->fetch_assoc();

if(!$p) die('Data tidak ditemukan');
if($p['status']!=='pending') die('Pengajuan sudah diproses');

/* NOMOR SURAT OTOMATIS */
$bulanRomawi = ['I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII'];
$nomor = "03 / 552 / Ds.M / ".$bulanRomawi[date('n')-1]." / ".date('Y');

$mysqli->begin_transaction();

try {

  $stmt = $mysqli->prepare("
    INSERT INTO surat_pengantar_kayu
    (nomor_surat,warga_id,jenis_kayu,rincian_kayu,lokasi_tujuan,tanggal_surat)
    VALUES (?,?,?,?,?,CURDATE())
  ");
  $stmt->bind_param(
    'sisss',
    $nomor,
    $p['warga_id'],
    $p['jenis_kayu'],
    $p['rincian_kayu'],
    $p['lokasi_tujuan']
  );

  if(!$stmt->execute()){
    throw new Exception($stmt->error);
  }

  $mysqli->query("
    UPDATE pengajuan_surat_pengantar_kayu
    SET status='acc', acc_at=NOW()
    WHERE id=$id
  ");

  $mysqli->commit();
  header("Location: surat_pengantar_kayu.php");
  exit;

} catch(Exception $e){
  $mysqli->rollback();
  die('Gagal ACC: '.$e->getMessage());
}
