<?php
// === SURAT IZIN BROWSER (CORS) ===
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

error_reporting(0); 
require_once '../config/database.php';

// Tangkap data dari Flutter
$data = json_decode(file_get_contents("php://input"));

if (!empty($data->cashier_name) && isset($data->total_price) && !empty($data->items)) {
    try {
        $pdo->beginTransaction();

        // 1. Cari ID Kasir berdasarkan Username
        $stmtUser = $pdo->prepare("SELECT id FROM users WHERE username = ?");
        $stmtUser->execute([$data->cashier_name]);
        $user = $stmtUser->fetch();
        $user_id = $user ? $user['id'] : 1; // Default ke 1 jika tidak ketemu

        $total_omzet_kotor = 0;
        $total_hpp = 0;

        // 2. Hitung Omzet, Modal (HPP), dan Potong Stok Otomatis
        foreach ($data->items as $item) {
            // Omzet Kotor = Harga Jual x Jumlah Beli
            $total_omzet_kotor += ($item->price * $item->qty);

            // Cari Modal (HPP) dari resep menu ini
            $stmtHpp = $pdo->prepare("
                SELECT SUM(r.usage_qty * i.price_per_unit) as modal
                FROM recipes r
                JOIN ingredients i ON r.ingredient_id = i.id
                WHERE r.product_id = ?
            ");
            $stmtHpp->execute([$item->id]);
            $hpp_row = $stmtHpp->fetch();
            $hpp_per_item = $hpp_row['modal'] ? $hpp_row['modal'] : 0;
            $total_hpp += ($hpp_per_item * $item->qty);

            // OTOMATIS POTONG STOK BAHAN BAKU (Sesuai Resep)
            $stmtRecipes = $pdo->prepare("SELECT ingredient_id, usage_qty FROM recipes WHERE product_id = ?");
            $stmtRecipes->execute([$item->id]);
            $recipes = $stmtRecipes->fetchAll();
            
            foreach ($recipes as $recipe) {
                $qty_deduct = $recipe['usage_qty'] * $item->qty;
                $updateStock = $pdo->prepare("UPDATE ingredients SET stock_qty = stock_qty - ? WHERE id = ?");
                $updateStock->execute([$qty_deduct, $recipe['ingredient_id']]);
            }
        }

        // 3. Hitung Diskon dan Keuntungan Bersih
        $discount_amount = $total_omzet_kotor - $data->total_price;
        $total_profit = $data->total_price - $total_hpp;

        // 4. Masukkan ke Tabel "transactions"
        $stmtTx = $pdo->prepare("INSERT INTO transactions (user_id, total_omzet, total_hpp, total_profit, discount_amount, transaction_date) VALUES (?, ?, ?, ?, ?, NOW())");
        $stmtTx->execute([$user_id, $total_omzet_kotor, $total_hpp, $total_profit, $discount_amount]);
        $transaction_id = $pdo->lastInsertId();

        // 5. Masukkan ke Tabel "transaction_details" (DI SINI YANG KITA PERBAIKI, TANPA KOLOM PRICE)
        $stmtDet = $pdo->prepare("INSERT INTO transaction_details (transaction_id, product_id, qty) VALUES (?, ?, ?)");
        foreach ($data->items as $item) {
            $stmtDet->execute([$transaction_id, $item->id, $item->qty]);
        }

        $pdo->commit();
        echo json_encode(["status" => "success", "message" => "Pesanan masuk web & Stok terpotong!"]);

    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(["status" => "error", "message" => "Database Error: " . $e->getMessage()]);
    }

} else {
    echo json_encode(["status" => "error", "message" => "Data keranjang tidak lengkap!"]);
}
?>