<?php
// GEMBOK ANTI-AKSES LANGSUNG
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(403);
    die("Akses Ditolak: Anda tidak diizinkan mengakses halaman ini secara langsung.");
}

session_start();

// Validasi Sesi: Pastikan eksekutor benar-benar user yang sudah login
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    die("Akses Ditolak: Sesi tidak valid atau Anda belum login.");
}

require_once '../config/database.php';
require_once '../includes/functions.php'; 

$user_id = $_SESSION['user_id'];
// Pastikan input products berupa array untuk mencegah manipulasi tipe data
$post_products = isset($_POST['products']) && is_array($_POST['products']) ? $_POST['products'] : []; 

// Tangkap data diskon dari form kasir dengan sanitasi ketat
$discount_type = htmlspecialchars($_POST['discount_type'] ?? 'none');
$discount_value = filter_var($_POST['discount_value'] ?? 0, FILTER_VALIDATE_FLOAT) ?: 0;

try {
    $pdo->beginTransaction();

    $total_omzet_kotor = 0;
    $total_hpp_hari_ini = 0;
    
    // 1. Buat transaksi baru untuk mendapatkan ID NOTA
    $stmt_trans = $pdo->prepare("INSERT INTO transactions (user_id, total_omzet, total_hpp, total_profit, transaction_date) VALUES (?, 0, 0, 0, NOW())");
    $stmt_trans->execute([$user_id]);
    
    // INI DIA ID NOTA-NYA:
    $transaction_id = $pdo->lastInsertId(); 

    foreach ($post_products as $product_id => $qty) {
        // Sanitasi ID dan Qty menjadi angka murni
        $qty = filter_var($qty, FILTER_VALIDATE_INT) ?: 0;
        $product_id = filter_var($product_id, FILTER_VALIDATE_INT) ?: 0;

        if ($qty <= 0 || $product_id <= 0) continue;

        $p_stmt = $pdo->prepare("SELECT selling_price FROM products WHERE id = ?");
        $p_stmt->execute([$product_id]);
        $p_data = $p_stmt->fetch();

        if (!$p_data) continue; // Cegah error jika ID produk fiktif dikirim

        $hpp_per_unit = calculateProductHPP($pdo, $product_id);
        $subtotal_omzet = $p_data['selling_price'] * $qty;
        $subtotal_hpp = $hpp_per_unit * $qty;

        $det_stmt = $pdo->prepare("INSERT INTO transaction_details (transaction_id, product_id, qty, subtotal_hpp) VALUES (?, ?, ?, ?)");
        $det_stmt->execute([$transaction_id, $product_id, $qty, $subtotal_hpp]);

        updateStock($pdo, $product_id, $qty);

        $total_omzet_kotor += $subtotal_omzet;
        $total_hpp_hari_ini += $subtotal_hpp;
    }

    // --- LOGIKA DISKON ---
    $discount_amount = 0;
    if ($discount_type === 'nominal') {
        $discount_amount = $discount_value;
    } elseif ($discount_type === 'percentage') {
        $discount_amount = ($total_omzet_kotor * $discount_value) / 100;
    }

    if ($discount_amount < 0) $discount_amount = 0;
    if ($discount_amount > $total_omzet_kotor) $discount_amount = $total_omzet_kotor;

    $total_omzet_bersih = $total_omzet_kotor - $discount_amount;
    $total_profit = $total_omzet_bersih - $total_hpp_hari_ini;

    // Update totalan akhir ke database
    $upd_stmt = $pdo->prepare("UPDATE transactions SET total_omzet = ?, total_hpp = ?, total_profit = ?, discount_type = ?, discount_value = ?, discount_amount = ? WHERE id = ?");
    $upd_stmt->execute([$total_omzet_kotor, $total_hpp_hari_ini, $total_profit, $discount_type, $discount_value, $discount_amount, $transaction_id]);

    $pdo->commit();

    // PENTING: Arahkan kembali ke kasir dan bawa ID NOTA untuk di-print!
    header("Location: ../modules/staff/production_input.php?status=success&print_id=" . $transaction_id);
    exit();

} catch (Exception $e) {
    $pdo->rollBack();
    die("Gagal simpan data: " . $e->getMessage());
}