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

if (isset($_POST['tambah'])) {
    $id_supplier = mysqli_real_escape_string($conn, $_POST['id_supplier']);
    $tanggal_pembelian = mysqli_real_escape_string($conn, $_POST['tanggal_pembelian']);
    $keterangan = mysqli_real_escape_string($conn, $_POST['keterangan']);
    $user_id = $_SESSION['id'];
    
    $items_data = json_decode($_POST['items_data'], true);
    
    if (empty($items_data)) {
        echo "<script>alert('Item pembelian tidak boleh kosong!'); window.history.back();</script>";
        exit;
    }
    
    $total_harga = 0;
    foreach ($items_data as $item) {
        $total_harga += $item['subtotal'];
    }
    
    $query_insert = "INSERT INTO pembelian (id_supplier, tanggal_pembelian, status, total_harga, keterangan, created_by)
                     VALUES ('$id_supplier', '$tanggal_pembelian', 'DRAFT', '$total_harga', '$keterangan', '$user_id')";
    
    if (mysqli_query($conn, $query_insert)) {
        $id_pembelian = mysqli_insert_id($conn);

        $all_success = true;
        foreach ($items_data as $item) {
            $id_obat = $item['id'];
            $jumlah = $item['jumlah'];
            $harga = $item['harga'];
            $subtotal = $item['subtotal'];
            
            $query_detail = "INSERT INTO pembelian_detail (id_pembelian, id_obat, jumlah, harga, subtotal)
                           VALUES ('$id_pembelian', '$id_obat', '$jumlah', '$harga', '$subtotal')";
            
            if (!mysqli_query($conn, $query_detail)) {
                $all_success = false;
                break;
            }
        }
        
        if ($all_success) {
            $pesan_kepala = "Pembelian baru #$id_pembelian dari Apoteker - Total: Rp " . number_format($total_harga, 0, ',', '.');
            $query_notif_kepala = "INSERT INTO notifikasi (kategori, pesan, status, role)
                                  VALUES ('PEMBELIAN_BARU', '$pesan_kepala', 'BARU', 'kepala_puskesmas')";
            mysqli_query($conn, $query_notif_kepala);
            
            $pesan_admin = "Pembelian baru #$id_pembelian dari Apoteker - Total: Rp " . number_format($total_harga, 0, ',', '.');
            $query_notif_admin = "INSERT INTO notifikasi (kategori, pesan, status, role)
                                VALUES ('PEMBELIAN_BARU', '$pesan_admin', 'BARU', 'admin')";
            mysqli_query($conn, $query_notif_admin);
            
            echo "<script>alert('Pembelian berhasil ditambahkan!'); window.location='pembelianapoteker.php';</script>";
        } else {
            echo "<script>alert('Gagal menambahkan detail pembelian!'); window.location='pembelianapoteker.php';</script>";
        }
    } else {
        echo "<script>alert('Gagal menambahkan pembelian: " . mysqli_error($conn) . "'); window.location='pembelianapoteker.php';</script>";
    }
}
?>