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

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

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

$nomor = "401/$c/SKTM/Ds.M/".date('m')."/".date('Y');

$mysqli->begin_transaction();

try {

  $stmt = $mysqli->prepare("
    INSERT INTO surat_tidak_mampu
    (nomor_surat,warga_id,tanggal_surat,keterangan)
    VALUES (?,?,CURDATE(),?)
  ");

  $stmt->bind_param(
    'sis',
    $nomor,
    $p['warga_id'],
    $p['keterangan']
  );

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

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

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

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