<?php
session_start();
include 'koneksi.php';

if (!isset($_SESSION['status']) || $_SESSION['status'] != "login") {
    header("Location: login.php?pesan=belum_login");
    exit();
}
function formatNPWP($npwp) {
    $npwp = preg_replace("/[^0-9]/", "", $npwp);
    if (empty($npwp)) return "-";
    
    $len = strlen($npwp);
    if ($len == 16) {
        return preg_replace("/(\d{2})(\d{3})(\d{3})(\d{1})(\d{3})(\d{3})/", "$1.$2.$3.$4-$5.$6", $npwp);
    } elseif ($len > 12) {
        return substr($npwp, 0, 2) . "." . substr($npwp, 2, 3) . "." . substr($npwp, 5, 3) . "." . substr($npwp, 8, 1) . "-" . substr($npwp, 9, 3) . "." . substr($npwp, 12);
    } elseif ($len > 9) {
        return substr($npwp, 0, 2) . "." . substr($npwp, 2, 3) . "." . substr($npwp, 5, 3) . "." . substr($npwp, 8, 1) . "-" . substr($npwp, 9);
    }
    // ... tambahkan kondisi lainnya jika perlu
    return $npwp;
}

$no_po = mysqli_real_escape_string($koneksi, $_GET['no']);

// 1. Ambil data profil perusahaan
$q_profil = mysqli_query($koneksi, "SELECT * FROM profil_perusahaan WHERE id=1 LIMIT 1");
$profil = mysqli_fetch_array($q_profil);

// 2. Ambil data PO utama
$q_po = mysqli_query($koneksi, "SELECT * FROM po_utama WHERE no_po = '$no_po'");
$data = mysqli_fetch_array($q_po);
if (!$data) { die("Data PO tidak ditemukan."); }

// 3. Ambil data supplier
$id_s = $data['id_supplier'];
$q_supp = mysqli_query($koneksi, "SELECT * FROM supplier WHERE id = '$id_s' LIMIT 1");
$supp = mysqli_fetch_array($q_supp);

$nama_vendor   = $supp['nama_supplier'] ?? "Vendor Tidak Terdaftar";
$alamat_vendor = $supp['alamat'] ?? "-";
$pic_vendor    = $supp['pic'] ?? "-";
$telp_vendor   = $supp['telp'] ?? "-";
$npwp_vendor   = $supp['npwp'] ?? "-";
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Detail Purchase Order - <?php echo $no_po; ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <style>
        body { font-family: 'Helvetica', Arial, sans-serif; font-size: 12px; color: #333; padding: 20px; background: #f4f4f4; margin: 0; }
        .no-print { max-width: 850px; margin: 0 auto 20px auto; text-align: left; }
        .btn-back { padding: 10px 20px; background: #2c3e50; color: white; text-decoration: none; border-radius: 8px; font-weight: 600; display: inline-flex; align-items: center; gap: 8px; font-size: 13px; }
        
        .paper { max-width: 850px; margin: auto; padding: 30px; background: #fff; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        .header { display: flex; border-bottom: 2px solid #e60000; padding-bottom: 15px; margin-bottom: 20px; align-items: center; }
        .logo { width: 110px; }
        .logo img { max-width: 100%; max-height: 80px; object-fit: contain; }
        .info-pt { flex: 1; padding-left: 20px; line-height: 1.6; }
        .title-po { text-align: right; }
        .title-po h1 { margin: 0; color: #e60000; font-size: 24px; }
        
        .grid { display: flex; justify-content: space-between; margin-bottom: 20px; gap: 15px; }
        .box { width: 48%; background: #fdfdfd; padding: 15px; border: 1px solid #eee; border-radius: 5px; min-height: 100px; line-height: 1.5; }
        
        table { width: 100%; border-collapse: collapse; margin-top: 10px; }
        table th { background: #333; color: #fff; padding: 10px; text-align: left; font-size: 11px; text-transform: uppercase; }
        table td { border-bottom: 1px solid #eee; padding: 12px 10px; vertical-align: top; }
        
        .total-wrapper { margin-top: 20px; float: right; width: 320px; }
        .total-table td { padding: 5px; border: none; }
        
        .badge-info { font-size: 11px; border-top: 1px dashed #ccc; margin-top: 8px; padding-top: 5px; }
    </style>
</head>
<body>

<div class="no-print">
    <a href="daftar_po.php" class="btn-back">
        <i class="fa-solid fa-arrow-left"></i> Kembali ke Daftar PO
    </a>
</div>

<div class="paper">
    <div class="header">
        <div class="logo">
            <img src="<?php echo $profil['logo'] ?? 'assets/logobest.png'; ?>" alt="Logo">
        </div>
        <div class="info-pt">
            <strong><?php echo $profil['nama_perusahaan'] ?? "PT. BERDUA SEJAHTERA TEKNIK"; ?></strong><br>
            <?php echo $profil['alamat'] ?? "Alamat belum diatur"; ?><br>
            Email: <?php echo $profil['email'] ?? "-"; ?> | Telp: <?php echo $profil['telp'] ?? "-"; ?>
        </div>
        <div class="title-po">
            <h1>PURCHASE ORDER</h1>
            <strong>No: <?php echo $no_po; ?></strong>
        </div>
    </div>

    <div class="grid">
        <div class="box">
            <small style="color:#888; font-weight:bold;">SUPPLIER:</small><br>
            <strong style="color:#e60000; font-size: 14px;"><?php echo $nama_vendor; ?></strong><br>
            <?php echo $alamat_vendor; ?><br>
            <div class="badge-info">
                <strong>PIC:</strong> <?php echo $pic_vendor; ?> | <strong>Telp:</strong> <?php echo $telp_vendor; ?><br>
                <strong>NPWP:</strong> <?php echo formatNPWP($npwp_vendor); ?>
            </div>
        </div>
        
        <div class="box">
            <small style="color:#888; font-weight:bold;">DETAIL PESANAN:</small><br>
            Tgl Rilis: <strong><?php echo date('d F Y', strtotime($data['tanggal_po'])); ?></strong><br>
            Status: <span style="color:green; font-weight:bold;">RELEASED</span><br>
            NPWP Buyer: <?php echo $profil['npwp'] ?? '-'; ?>
        </div>
    </div>

    <table>
        <thead>
            <tr>
                <th width="5%" style="text-align: center;">NO</th>
                <th width="50%">Item Description</th>
                <th width="10%" style="text-align: center;">QTY</th>
                <th width="15%" style="text-align: right;">HARGA (Rp)</th>
                <th width="20%" style="text-align: right;">SUBTOTAL (Rp)</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $no = 1;
            $hitung_subtotal = 0;
            $q_item = mysqli_query($koneksi, "SELECT * FROM po_detail WHERE no_po = '$no_po'");
            while ($it = mysqli_fetch_array($q_item)) {
                $sub_item = $it['qty'] * $it['harga'];
                $hitung_subtotal += $sub_item;
                echo "<tr>
                        <td align='center'>".$no++."</td>
                        <td><strong>".$it['nama_barang']."</strong></td>
                        <td align='center'>".$it['qty']."</td>
                        <td align='right'>".number_format($it['harga'], 0, ',', '.')."</td>
                        <td align='right'><strong>".number_format($sub_item, 0, ',', '.')."</strong></td>
                      </tr>";
            }

            // Logika perhitungan pajak (Sama dengan print_po)
            $val_subtotal = ($data['subtotal'] > 0) ? $data['subtotal'] : $hitung_subtotal;
            $val_diskon   = ($data['diskon'] > 0) ? $data['diskon'] : 0;
            $val_ppn      = ($data['ppn'] > 0) ? $data['ppn'] : ($val_subtotal - $val_diskon) * 0.11;
            $val_grand    = ($data['total'] > 0) ? $data['total'] : ($val_subtotal - $val_diskon + $val_ppn);
            ?>
        </tbody>
    </table>

    <div class="total-wrapper">
        <table class="total-table" style="width: 100%;">
            <tr>
                <td>Subtotal</td>
                <td style="text-align: right;">Rp <?php echo number_format($val_subtotal, 0, ',', '.'); ?></td>
            </tr>
            <tr>
                <td>Diskon</td>
                <td style="text-align: right;">Rp <?php echo number_format($val_diskon, 0, ',', '.'); ?></td>
            </tr>
            <tr>
                <td>PPN (11%)</td>
                <td style="text-align: right;">Rp <?php echo number_format($val_ppn, 0, ',', '.'); ?></td>
            </tr>
            <tr style="border-top: 2px solid #333; font-weight: bold; font-size: 14px;">
                <td style="padding-top: 10px;">GRAND TOTAL</td>
                <td style="text-align: right; padding-top: 10px; color: #d32f2f;">Rp <?php echo number_format($val_grand, 0, ',', '.'); ?></td>
            </tr>
        </table>
    </div>
    <div style="clear: both;"></div>
</div>

</body>
</html>