<?php
require_once __DIR__ . '/asset/phpword-master/src/PhpWord/Autoloader.php';
\PhpOffice\PhpWord\Autoloader::register();
include "koneksi.php";

use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\SimpleType\Jc;

/*
|--------------------------------------------------------------------------
| AMBIL DATA
|--------------------------------------------------------------------------
*/

$nofile = $_GET['nofile'];

$sqle = mysqli_query($konek, "SELECT r.*,c.*,p.nama_pic,p.telp_pic,u.*
FROM raxi_ps r
INNER JOIN customer c ON r.idcustomer = c.idcustomer
INNER JOIN pic p ON p.idcustomer=c.idcustomer
INNER JOIN detail_raxips d ON d.idraxips = r.idraxips 
INNER JOIN unit u ON d.idunit = u.idunit
WHERE nofile_raxips = '$nofile'");

$rows = mysqli_fetch_assoc($sqle);

$cabang = str_contains($nofile, "SV-TG") ? "Tangerang" : "Surabaya";

$bulan = [1 => 'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
$t = strtotime($rows['tgl_raxips']);
$tanggal = date('j', $t) . ' ' . $bulan[(int)date('n', $t)] . ' ' . date('Y', $t);

/*
|--------------------------------------------------------------------------
| PHPWORD
|--------------------------------------------------------------------------
*/
$phpWord = new PhpWord();

$phpWord->setDefaultParagraphStyle([
    'spaceBefore' => 0,
    'spaceAfter'  => 0,
    'lineHeight'  => 1
]);

$section = $phpWord->addSection([
    'paperSize'    => 'A4',
    'orientation'  => 'portrait',
    'marginTop'    => 200,
    'marginLeft'   => 400,
    'marginRight'  => 400,
    'marginBottom' => 200,
    'headerHeight' => 200,
    'footerHeight' => 200,
]);

/*
|--------------------------------------------------------------------------
| HEADER
|--------------------------------------------------------------------------
*/
$header = $section->addHeader();

// Style table header (full width + garis bawah)
$phpWord->setDefaultFontName('Calibri');
$phpWord->addTableStyle('HeaderTable', [
    'width' => 100 * 50,
    'unit'  => 'pct',
    'borderBottomSize' => 12,
    'borderBottomColor' => '000000',
]);

$tableHeader = $header->addTable('HeaderTable');

$tableHeader->addRow();

// KOLOM LOGO
$tableHeader->addCell(3000, ['valign' => 'center'])
    ->addImage(
        'asset/gambar/logo-raxprint.png',
        [
            'width' => 160,
            // 'height' => 108,
            'alignment' => Jc::START
        ]
    );
//KOLOM KOSONG
$cellkosong = $tableHeader->addCell(200);
// KOLOM TEXT
$cellText = $tableHeader->addCell(7800, [
    'marginLeft' => 1000
]);

$cellText->addText(
    'PT. RAXI INDONESIA',
    ['bold' => true, 'size' => 20],
    ['spaceAfter' => 0]
);

$cellText->addText(
    'Material Handling Equipment | Sale | Rent | Service | www.materialhandling.co.id',
    ['bold' => true, 'size' => 9],
    ['spaceAfter' => 0]
);

$cellText->addText(
    'Surabaya : Gedung Graha Pena Lantai 5, Jl. Ahmad Yani No. 88 RT 007 RW 003, Ketintang, Gayungan, Surabaya | 031-30008273',
    ['size' => 9],
    ['spaceAfter' => 0]
);

$cellText->addText(
    'Jakarta : Menara Rajawali Level 7 Jl. DR. Ide Anak Agung Gde Agung, Jakarta Selatan | 021-29490627',
    ['size' => 9],
    ['spaceAfter' => 0]
);

$cellText->addText(
    'Tangerang : Jl. Raya Cibar Barat No.9C, BSD Serpong, Tangerang Selatan | 021-75671297',
    ['size' => 9],
    ['spaceAfter' => 0]
);

$cellText->addText(
    'sales@materialhandling.co.id | marketing@raxi.co.id | sby@raxi.co.id | jkt@raxi.co.id',
    ['size' => 9]
);
/*
|--------------------------------------------------------------------------
| FOOTER
|--------------------------------------------------------------------------
*/
$footer = $section->addFooter();
$footer->addImage('asset/gambar/foot-rax.png', [
    'width' => 550
]);

/*
|--------------------------------------------------------------------------
| TANGGAL
|--------------------------------------------------------------------------
*/
$section->addText("$cabang, $tanggal", [], ['alignment' => Jc::END]);
$section->addTextBreak();

/*
|--------------------------------------------------------------------------
| TABLE INFO ATAS
|--------------------------------------------------------------------------
*/
$tableInfo = $section->addTable();

function rowInfo($table, $a, $b, $c, $d = null, $e = null, $f = null)
{
    $table->addRow();
    $table->addCell(900)->addText($a, ['bold' => true]);
    $table->addCell(100)->addText(':');
    $table->addCell(5800)->addText($c);
    if ($d) {
        $table->addCell(900)->addText($d, ['bold' => true]);
        $table->addCell(100)->addText(':');
        $table->addCell(3000)->addText($f);
    }
}

rowInfo($tableInfo, 'No File', '', $rows['nofile_raxips'], 'Up', '', $rows['nama_pic']);
rowInfo($tableInfo, 'Kepada', '', $rows['bu'] . $rows['nama_customer'], 'Telp / Hp', '', $rows['telp_pic'] . ' / ' . $rows['telp']);
rowInfo($tableInfo, 'Alamat', '', $rows['alamat'], 'Email', '', $rows['email']);

$section->addTextBreak();

/*
|--------------------------------------------------------------------------
| PARAGRAF PEMBUKA
|--------------------------------------------------------------------------
*/
$section->addText("Dengan Hormat,");

$textrun = $section->addTextRun();
$textrun->addText("Bersama ini kami ");
$textrun->addText("PT. RAXI INDONESIA", ['bold' => true]);
$textrun->addText(" bergerak di bidang ");
$textrun->addText("Penjualan, Sewa, serta Perbaikan Material Handling di Indonesia", ['italic' => true]);
$textrun->addText(" bermaksud menawarkan harga sebagai berikut:");

$section->addTextBreak();

/*
|--------------------------------------------------------------------------
| TABLE DETAIL
|--------------------------------------------------------------------------
*/
$table = $section->addTable([
    'borderSize' => 6,
    'borderColor' => '000000',
]);

// HEADER
$table->addRow();
$table->addCell(600)->addText('No', ['bold' => true], ['alignment' => Jc::CENTER]);
$table->addCell(2000)->addText('Uraian', ['bold' => true], ['alignment' => Jc::CENTER]);
$table->addCell(500)->addText('QTY', ['bold' => true], ['alignment' => Jc::CENTER]);
$table->addCell(5000)->addText('Keterangan', ['bold' => true], ['alignment' => Jc::CENTER]);
$table->addCell(1500)->addText('Harga Satuan', ['bold' => true], ['alignment' => Jc::CENTER]);
$table->addCell(1500)->addText('Harga', ['bold' => true], ['alignment' => Jc::CENTER]);

/*
|--------------------------------------------------------------------------
| LOOP DETAIL
|--------------------------------------------------------------------------
*/
$idraxips = $rows['idraxips'];
$sql = mysqli_query($konek, "SELECT * FROM detail_raxips WHERE idraxips='$idraxips'");
$no = 1;

while ($unit = mysqli_fetch_assoc($sql)) {

    $iddetail = $unit['iddetail_raxips'];

    $q = mysqli_query($konek, "
        SELECT s.jenis_service as ket,j.harga_serviceraxi as harga,
        j.qty_service as qty,j.totalservice_raxi as total,j.keterangan as keterangan
        FROM uraianraxips_service j
        INNER JOIN jenis_service s ON j.idjenis_service=s.idjenis_service
        WHERE iddetail_raxips='$iddetail'
        UNION ALL
        SELECT b.nama_barang as ket,ub.harga_barangraxi,ub.qty,ub.totalbarang_raxi,ub.keterangan as keterangan
        FROM uraianraxips_barang ub
        INNER JOIN barang b ON ub.idbarang=b.idbarang
        WHERE iddetail_raxips='$iddetail'
    ");

    $data = mysqli_num_rows($q);
    $i = 0;
    $subtotal = 0;

    while ($d = mysqli_fetch_assoc($q)) {

        $table->addRow();

        if ($i == 0) {
            $table->addCell(600, ['vMerge' => 'restart', 'valign' => 'center'])->addText($no, [], ['alignment' => Jc::CENTER]);
            $table->addCell(2000, ['vMerge' => 'restart', 'valign' => 'center'])->addText($rows['nama_unit'], [], ['alignment' => Jc::CENTER]);
        } else {
            $table->addCell(600, ['vMerge' => 'continue']);
            $table->addCell(2000, ['vMerge' => 'continue']);
        }

        $table->addCell(500, ['valign' => 'center'])->addText($d['qty'], [], ['alignment' => Jc::CENTER]);

        //KETERANGAN
        $cell = $table->addCell(5000, ['valign' => 'center']); // width 4000
        $textrun = $cell->addTextRun(['alignment' => Jc::START]);

        // Pisahkan ket dan keterangan
        $ket = str_replace('&', '&amp;', $d['ket']); // escape &
        $textrun->addText($ket, ['bold' => true]);
        $textrun->addTextBreak();

        // Keterangan baris per baris
        $lines = explode("\n", $d['keterangan']);
        foreach ($lines as $line) {
            $line = trim(str_replace('&', '&amp;', $line)); // escape & dan trim spasi
            if ($line !== '') {
                $textrun->addText($line);
                $textrun->addTextBreak();
            }
        }
        $table->addCell(1500, ['valign' => 'center'])->addText("Rp " . number_format($d['harga'], 0, ',', '.'));
        $table->addCell(1500, ['valign' => 'center'])->addText("Rp " . number_format($d['total'], 0, ',', '.'));

        $subtotal += $d['total'];
        $i++;
    }

    $ppn = $subtotal * 0.11;
    $total = $subtotal + $ppn;

    // SUBTOTAL
    $table->addRow();
    $cellStyle = [
        'borderLeftSize'   => 0,
        'borderBottomSize' => 0,
        'borderTopSize' => 0,
        'borderLeftColor'  => 'FFFFFF',
        'borderBottomColor' => 'FFFFFF',
        'borderTopColor' => 'FFFFFF',
        'gridSpan' => 2,
    ];
    $table->addCell(2000, $cellStyle)->addText('');
    $table->addCell(5400, ['gridSpan' => 3])->addText("Subtotal", ['bold' => true], ['alignment' => Jc::CENTER]);
    $table->addCell(1500)->addText("Rp " . number_format($subtotal, 0, ',', '.'));

    // PPN
    $table->addRow();
    $table->addCell(2000, $cellStyle)->addText('');
    $table->addCell(5400, ['gridSpan' => 3])->addText("PPN 11%", ['bold' => true], ['alignment' => Jc::CENTER]);
    $table->addCell(1500)->addText("Rp " . number_format($ppn, 0, ',', '.'));

    // TOTAL
    $table->addRow();
    $table->addCell(2000, $cellStyle)->addText('');
    $table->addCell(5400, ['gridSpan' => 3])->addText("TOTAL", ['bold' => true], ['alignment' => Jc::CENTER]);
    $table->addCell(1500)->addText("Rp " . number_format($total, 0, ',', '.'));

    $section->addTextBreak();
    $no++;
}

/*
|--------------------------------------------------------------------------
| NOTE
|--------------------------------------------------------------------------
*/
$textrun = $section->addTextRun(['alignment' => Jc::BOTH]);
$textrun->addText('Note : ', ['bold' => true]);
$textrun->addText(
    'Unit ' . $rows['status_checkraxips'] . ' dilakukan pengecekan oleh teknisi PT Raxi Indonesia'
);

$section->addTextBreak();
/*
|--------------------------------------------------------------------------
| KETERANGAN
|--------------------------------------------------------------------------
*/
$section->addText("Keterangan :", ['bold' => true]);

// Item bullet biasa
$section->addListItem("Gratis biaya pengiriman Ke Surabaya, Sidoarjo, dan Jabodetabek", 0, null, \PhpOffice\PhpWord\Style\ListItem::TYPE_BULLET_FILLED);
$section->addListItem("Total harga sudah termasuk PPN", 0, null, \PhpOffice\PhpWord\Style\ListItem::TYPE_BULLET_FILLED);
$section->addListItem("Pengerjaan service dimulai setelah PO dan/atau konfirmasi diterima", 0, null, \PhpOffice\PhpWord\Style\ListItem::TYPE_BULLET_FILLED);

// Bullet dengan teks bergaya (italic)
$listRun = $section->addListItemRun(0, \PhpOffice\PhpWord\Style\ListItem::TYPE_BULLET_FILLED);
$listRun->addText("Sistem Pembayaran ");
$listRun->addText("Cash On Delivery", ['italic' => true]);

// Lanjut bullet biasa
$section->addListItem("Surat penawaran ini berlaku 1 minggu", 0, null, \PhpOffice\PhpWord\Style\ListItem::TYPE_BULLET_FILLED);
$section->addListItem("Kunjungi www.materialhandling.com untuk info produk material handling lainnya dan www.servicehandpallet.com untuk pelayanan service", 0, null, \PhpOffice\PhpWord\Style\ListItem::TYPE_BULLET_FILLED);

$section->addTextBreak();
/*
|--------------------------------------------------------------------------
| DEMIKIAN
|--------------------------------------------------------------------------
*/

$section->addText("Demikian surat penawaran ini, apabila kurang jelas dapat ditanyakan langsung kepada kami dan kami tunggu kepastian ordernya. Atas perhatian dan kerjasamanya, terima kasih.");
$section->addTextBreak();

/*
|--------------------------------------------------------------------------
| TTD
|--------------------------------------------------------------------------
*/
$section->addText("Hormat Kami,");
$section->addText("Marketing Division PT. RAXI INDONESIA", ['bold' => true]);

if ($cabang == "Tangerang") {
    $section->addImage('asset/gambar/ttd aidah (raxi sv tgr).png', ['width' => 120]);
    $section->addText("Aidah", ['bold' => true, 'underline' => 'single']);
    $section->addText("0812 2430 2982");
} else {
    $section->addImage('asset/gambar/ttd ditya kusuma (raxi sv sby).png', ['width' => 120]);
    $section->addText("Ditya Kusuma Putri", ['bold' => true, 'underline' => 'single']);
    $section->addText("0812 2430 2982");
}

$section->addPageBreak();

/*
|--------------------------------------------------------------------------
| GAMBAR CONTOH
|--------------------------------------------------------------------------
*/
$section->addText("Contoh Pengerjaan Service Hydraulic di PT. RAXI INDONESIA", ['bold' => true], ['alignment' => Jc::CENTER]);
$table = $section->addTable(['alignment' => \PhpOffice\PhpWord\SimpleType\Jc::CENTER]);

$table->addRow();
$table->addCell(5000)->addImage('asset/gambar/kiri.png', ['width' => 250]);
$table->addCell(5000)->addImage('asset/gambar/kanan.png', ['width' => 250]);

/*
|--------------------------------------------------------------------------
| OUTPUT
|--------------------------------------------------------------------------
*/
header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="Penawaran_' . $nofile . '.docx"');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');

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