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

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

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

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

$mysqli->begin_transaction();

try {

  $stmt = $mysqli->prepare("
    INSERT INTO surat_pindah
    (nomor_surat, warga_id, tujuan_dusun, tujuan_desa,
     tujuan_kecamatan, tujuan_kabupaten, tujuan_provinsi, alasan_pindah)
    VALUES (?,?,?,?,?,?,?,?)
  ");

  $stmt->bind_param(
    'sissssss',
    $nomor,
    $p['warga_id'],
    $p['tujuan_dusun'],
    $p['tujuan_desa'],
    $p['tujuan_kecamatan'],
    $p['tujuan_kabupaten'],
    $p['tujuan_provinsi'],
    $p['alasan_pindah']
  );

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

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

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

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