<?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_domisili WHERE id=$id
")->fetch_assoc();

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

/* NOMOR SURAT */
$urut = $mysqli->query("SELECT COUNT(*) c FROM surat_keterangan_domisili")
               ->fetch_assoc()['c'] + 1;

$romawi = ['','I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII'];
$nomor = "017/$urut/Ds.M/".$romawi[date('n')]."/".date('Y');

$mysqli->begin_transaction();

try {

  $mysqli->query("
    INSERT INTO surat_keterangan_domisili
    (warga_id, nomor_surat, tanggal_surat)
    VALUES ('{$p['warga_id']}','$nomor',CURDATE())
  ");

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

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

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