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

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

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

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

$mysqli->begin_transaction();

try {

  $stmt = $mysqli->prepare("
    INSERT INTO surat_merantau
    (nomor_surat, warga_id, tujuan_merantau)
    VALUES (?,?,?)
  ");
  $stmt->bind_param(
    'sis',
    $nomor,
    $p['warga_id'],
    $p['tujuan_merantau']
  );

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

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

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

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