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

if(!isset($_GET['id'])) die('ID tidak valid');
$id = (int)$_GET['id'];

$p = $mysqli->query("
  SELECT * FROM pengajuan_surat_ijin_keramaian WHERE id=$id
")->fetch_assoc();

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

/* NOMOR SURAT */
$bulanRomawi = ['I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII'];
$urut = $mysqli->query("SELECT COUNT(*) c FROM surat_ijin_keramaian")
               ->fetch_assoc()['c'] + 1;

$nomor = sprintf(
  "001/%03d/Ds.M/%s/%s",
  $urut,
  $bulanRomawi[date('n')-1],
  date('Y')
);

$mysqli->begin_transaction();

try {

  $stmt = $mysqli->prepare("
    INSERT INTO surat_ijin_keramaian
    (nomor_surat, warga_id, umur, jenis_kelamin, pekerjaan, agama, alamat,
     jenis_acara, hari_tanggal, waktu, tempat_acara)
    VALUES (?,?,?,?,?,?,?,?,?,?,?)
  ");

  $stmt->bind_param(
    "siissssssss",
    $nomor,
    $p['warga_id'],
    $p['umur'],
    $p['jenis_kelamin'],
    $p['pekerjaan'],
    $p['agama'],
    $p['alamat'],
    $p['jenis_acara'],
    $p['hari_tanggal'],
    $p['waktu'],
    $p['tempat_acara']
  );

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

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

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

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