<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require "../config.php";

/*
|--------------------------------------------------------------------------
| AUTOLOAD MANUAL PHPWORD
|--------------------------------------------------------------------------
*/
spl_autoload_register(function ($class) {
    $prefix = 'PhpOffice\\PhpWord\\';
    $base_dir = __DIR__ . '/vendor/src/PhpWord/';

    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        return;
    }

    $relative_class = substr($class, $len);
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';

    if (file_exists($file)) {
        require $file;
    } else {
        die("File tidak ditemukan: " . $file);
    }
});

use PhpOffice\PhpWord\PhpWord;

// =====================
// VALIDASI INPUT
// =====================
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

$q = $conn->query("SELECT * FROM pengajuan WHERE id=$id");
$d = $q->fetch_assoc();

if (!$d) {
    die("Data tidak ditemukan");
}

// =====================
// AUTO FIX PATH GAMBAR
// =====================
$root = $_SERVER['DOCUMENT_ROOT'];

function cleanFile($file){
    return str_replace(['uploads/', '/uploads/'], '', $file);
}

function findFile($filename, $root){
    $filename = cleanFile($filename);

    $paths = [
        $root . "/petesa/uploads/" . $filename,
        $root . "/uploads/" . $filename,
        $root . "/petesa/" . $filename,
    ];

    foreach ($paths as $file) {
        if (!empty($filename) && file_exists($file)) {
            return $file;
        }
    }
    return '';
}

$file1 = findFile($d['file_surat'], $root);
$file2 = findFile($d['file_identitas'], $root);

// =====================
// INIT PHPWORD
// =====================
$phpWord = new PhpWord();
$section = $phpWord->addSection();

// =====================
// JUDUL
// =====================
$section->addText(
    'DETAIL PERMOHONAN',
    ['bold'=>true, 'size'=>14],
    ['alignment'=>'center']
);

// =====================
// GAMBAR SURAT
// =====================
$section->addText(
    'Surat Permohonan',
    ['bold'=>true],
    ['alignment'=>'center']
);

if ($file1) {
    $section->addImage($file1, [
        'width' => 450,
        'height' => 625,
        'alignment' => 'center'
    ]);
} else {
    $section->addText('Gambar tidak ditemukan: ' . $d['file_surat']);
}

// =====================
// JUDUL IDENTITAS
// =====================
$section->addTextBreak();
$section->addText(
    'DETAIL IDENTITAS',
    ['bold'=>true, 'size'=>12],
    ['alignment'=>'center']
);


// =====================
// style tabel (ADA GARIS)
$tableStyle = [
    'borderSize' => 6,
    'borderColor' => '000000',
    'cellMargin' => 80
];

$phpWord->addTableStyle('tableIdentitas', $tableStyle);

$table = $section->addTable('tableIdentitas');

// fungsi row (2 kolom)
function row($table, $label, $value){
    // tinggi row supaya valign jalan
    $table->addRow(500);

    // style cell (vertikal tengah)
    $cellStyle = ['valign' => 'center'];

    // style paragraf (hapus space after & before)
    $paraStyle = [
        'spaceAfter' => 0,
        'spaceBefore' => 0
    ];

    // kolom kiri
    $table->addCell(4000, $cellStyle)
          ->addText($label, ['bold'=>true], $paraStyle);

    // kolom kanan
    $table->addCell(8000, $cellStyle)
          ->addText($value, [], $paraStyle);
}
row($table, "Nama", $d['nama']);
row($table, "No Handphone", $d['no_hp']);
row($table, "Email", $d['email']);
row($table, "Instansi", $d['instansi']);
row($table, "Pekerjaan", $d['pekerjaan']);
row($table, "Alamat", $d['alamat']);
row($table, "Kota/Kabupaten", $d['kota']);
row($table, "NIK", $d['nik']);
row($table, "Jenis Permohonan", $d['jenis_permohonan']);
row($table, "Tujuan Permohonan", $d['tujuan']);
row($table, "Tanggal Permohonan", $d['tanggal_permohonan']);

// =====================
// GAMBAR IDENTITAS
// =====================
$section->addTextBreak();
$section->addText(
    'File Identitas',
    ['bold'=>true],
    ['alignment'=>'center']
);

if ($file2) {
    $section->addImage($file2, [
        'width' => 400,
        'alignment' => 'center'
    ]);
} else {
    $section->addText('Gambar tidak ditemukan: ' . $d['file_identitas']);
}

// =====================
// OUTPUT
// =====================
header("Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document");
header("Content-Disposition: attachment; filename=Detail_Permohonan.docx");

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save("php://output");