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

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

/* NOMOR SURAT */
$urut = $mysqli->query("SELECT COUNT(*) c FROM surat_keterangan_hilang")
               ->fetch_assoc()['c'] + 1;
$nomor = "$urut/145/Ds.M/VI/".date('Y');

$mysqli->begin_transaction();

try {

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

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

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

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

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

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