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

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

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

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

$mysqli->begin_transaction();

try {

  /* INSERT KE SURAT RESMI */
  $stmt = $mysqli->prepare("
    INSERT INTO surat_penghasilan_ortu
    (nomor_surat, warga_id, pekerjaan_ortu, penghasilan_ortu, alasan_surat, tanggal_surat)
    VALUES (?,?,?,?,?,CURDATE())
  ");

  $stmt->bind_param(
    'sisss',
    $nomor,
    $p['ortu_id'],
    $p['pekerjaan_ortu'],
    $p['penghasilan'],
    $p['keperluan']
  );

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

  /* UPDATE STATUS PENGAJUAN */
  $mysqli->query("
    UPDATE pengajuan_penghasilan_ortu
    SET status='acc', acc_at=NOW()
    WHERE id=$id
  ");

  $mysqli->commit();

  header("Location: surat_penghasilan_ortu.php");
  exit;

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