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

// Pengecekan Sesi
if (!isset($_SESSION['user_id'])) {
    die("Error: Anda belum login. Silakan login kembali.");
}
if (!isset($_SESSION['user_cabang'])) {
    die("Error: Data sesi cabang hilang. Silakan login kembali.");
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Pastikan ID Supplier ada
    if (empty($_POST['id_supplier'])) {
        die("Error: Supplier belum dipilih.");
    }

    $id_supplier = mysqli_real_escape_string($conn, $_POST['id_supplier']);
    $no_po       = "PO-" . date('YmdHis'); 
    $tgl_po      = date('Y-m-d');
    $id_cabang   = $_SESSION['user_cabang'];

    $query = "INSERT INTO purchase_order (no_po, id_supplier, tgl_po, id_cabang) 
              VALUES ('$no_po', '$id_supplier', '$tgl_po', '$id_cabang')";
    
    // Debugging: Cek apakah query berhasil
    if (mysqli_query($conn, $query)) {
        $id_po_baru = mysqli_insert_id($conn);
        header("Location: ../purchase-order.php?id_po=$id_po_baru");
        exit(); 
    } else {
        // Ini akan menampilkan error MySQL yang sebenarnya
        die("Error MySQL (" . mysqli_errno($conn) . "): " . mysqli_error($conn));
    }
} else {
    // Jika user akses langsung file ini
    header("Location: ../purchase-order.php");
    exit();
}
?>