<?php

/*
=========================================================
PROSES STOCK OUT ADMIN
=========================================================

Aturan:

1. Stock fisik dikurangi.
2. Reserved dikurangi terlebih dahulu.
3. Reserved tidak boleh minus.
4. Dus dan Pcs berdiri sendiri.
5. Request yang terpenuhi dapat diproses.
6. Tidak ada pengurangan stock ketika SPG membuat request.
=========================================================
*/

function process_stock_out(
    PDO $pdo,
    int $productId,
    float $quantity,
    string $unit
) {

    if ($productId <= 0) {
        throw new Exception('Produk tidak valid.');
    }

    if ($quantity <= 0) {
        throw new Exception('Jumlah stock out harus lebih dari 0.');
    }

    if (!in_array($unit, ['dus', 'pcs'], true)) {
        throw new Exception('Satuan tidak valid.');
    }


    /*
    =====================================================
    TRANSACTION
    =====================================================
    */

    $pdo->beginTransaction();

    try {

        /*
        =================================================
        KUNCI PRODUK
        =================================================
        */

        $stmt = $pdo->prepare("
            SELECT
                id,
                name,
                stock_dus,
                stock_pcs,
                reserved_dus,
                reserved_pcs
            FROM products
            WHERE id = ?
            FOR UPDATE
        ");

        $stmt->execute([
            $productId
        ]);

        $product =
            $stmt->fetch(PDO::FETCH_ASSOC);


        if (!$product) {

            throw new Exception(
                'Produk tidak ditemukan.'
            );
        }


        /*
        =================================================
        AMBIL NILAI STOK
        =================================================
        */

        $stockDus =
            (float)$product['stock_dus'];

        $stockPcs =
            (float)$product['stock_pcs'];

        $reservedDus =
            (float)$product['reserved_dus'];

        $reservedPcs =
            (float)$product['reserved_pcs'];


        /*
        =================================================
        STOCK OUT DUS
        =================================================
        */

        if ($unit === 'dus') {

            if ($quantity > $stockDus) {

                throw new Exception(
                    'Stok Dus tidak mencukupi. ' .
                    'Stok tersedia: ' .
                    $stockDus .
                    ' Dus.'
                );
            }


            /*
            ---------------------------------------------
            KURANGI STOCK FISIK
            ---------------------------------------------
            */

            $stockDus -= $quantity;


            /*
            ---------------------------------------------
            KURANGI RESERVED
            ---------------------------------------------

            Reserved hanya dikurangi sebanyak
            jumlah yang memang masih dipesan.

            Contoh:

            reserved = 3
            stock out = 5

            reserved menjadi 0
            stock berkurang 5.
            */

            $reservedUsed =
                min(
                    $quantity,
                    $reservedDus
                );

            $reservedDus -=
                $reservedUsed;
        }


        /*
        =================================================
        STOCK OUT PCS
        =================================================
        */

        if ($unit === 'pcs') {

            if ($quantity > $stockPcs) {

                throw new Exception(
                    'Stok Pcs tidak mencukupi. ' .
                    'Stok tersedia: ' .
                    $stockPcs .
                    ' Pcs.'
                );
            }


            /*
            ---------------------------------------------
            KURANGI STOCK FISIK
            ---------------------------------------------
            */

            $stockPcs -= $quantity;


            /*
            ---------------------------------------------
            KURANGI RESERVED
            ---------------------------------------------
            */

            $reservedUsed =
                min(
                    $quantity,
                    $reservedPcs
                );

            $reservedPcs -=
                $reservedUsed;
        }


        /*
        =================================================
        UPDATE PRODUK
        =================================================
        */

        $update = $pdo->prepare("
            UPDATE products
            SET
                stock_dus = ?,
                stock_pcs = ?,
                reserved_dus = ?,
                reserved_pcs = ?
            WHERE id = ?
        ");

        $update->execute([

            $stockDus,
            $stockPcs,
            $reservedDus,
            $reservedPcs,
            $productId

        ]);


        /*
        =================================================
        COMMIT
        =================================================
        */

        $pdo->commit();


        return true;


    } catch (Throwable $e) {

        if ($pdo->inTransaction()) {

            $pdo->rollBack();
        }

        throw $e;
    }
}