<?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'];

/* ================= DATA PENGAJUAN ================= */
$p = $mysqli->query("
  SELECT *
  FROM pengajuan_surat_usaha
  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_usaha")
            ->fetch_assoc()['total'] + 1;

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

/* ================= TRANSAKSI ================= */
$mysqli->begin_transaction();

try {

  /* INSERT KE SURAT USAHA RESMI */
  $stmt = $mysqli->prepare("
    INSERT INTO surat_usaha
    (nomor_surat, warga_id, bidang_usaha, alamat_usaha, tahun_berdiri, tanggal_surat)
    VALUES (?,?,?,?,?,CURDATE())
  ");

  $stmt->bind_param(
    'sisss',
    $nomor,
    $p['warga_id'],
    $p['bidang_usaha'],
    $p['alamat_usaha'],
    $p['tahun_berdiri']
  );

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

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

  $mysqli->commit();

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

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