<?php
// FILE: konfirmasipembelian.php
include 'koneksi.php';

if (isset($_POST['konfirmasi'])) {
    $id_pembelian = $_POST['id_pembelian'];

    // Cek apakah pembelian ada dan statusnya DRAFT
    $cek_query = "SELECT status FROM pembelian WHERE id_pembelian = '$id_pembelian'";
    $cek_result = mysqli_query($conn, $cek_query);
    $cek_data = mysqli_fetch_assoc($cek_result);

    if (!$cek_data) {
        echo "<script>alert('Data pembelian tidak ditemukan!'); window.location='pembelian.php';</script>";
    } elseif ($cek_data['status'] != 'DRAFT') {
        echo "<script>alert('Pembelian ini sudah dikonfirmasi sebelumnya!'); window.location='pembelian.php';</script>";
    } else {
        // Update status pembelian menjadi APPROVED
        $query = "UPDATE pembelian SET status = 'APPROVED' WHERE id_pembelian = '$id_pembelian'";
        
        if (mysqli_query($conn, $query)) {
            echo "<script>alert('Pembelian berhasil dikonfirmasi!'); window.location='pembelian.php';</script>";
        } else {
            echo "<script>alert('Gagal mengkonfirmasi pembelian.'); window.location='pembelian.php';</script>";
        }
    }
}
?>