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

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

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

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

$mysqli->begin_transaction();

try {

  $stmt = $mysqli->prepare("
    INSERT INTO surat_kuasa
    (nomor_surat,pemberi_id,penerima_id,keperluan)
    VALUES (?,?,?,?)
  ");
  $stmt->bind_param(
    'siis',
    $nomor,
    $p['pemberi_id'],
    $p['penerima_id'],
    $p['keperluan']
  );

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

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

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

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