<?php
require_once __DIR__ . '/../library/auth.php'; 
require_once __DIR__ . '/../library/audit_log.php';
$school_id = $_SESSION['school_id'];

// ======================================================
// LOGIN CHECK
// ======================================================

if (!isset($_SESSION['user_id'])) {

    header("Location: ../login.php");
    exit;
}

$school_id = $_SESSION['school_id'];

$page_title = 'Issue / Return Inventory';


// ======================================================
// ISSUE / RETURN LOGIC
// ======================================================

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit_type'])) {

    $item_id   = intval($_POST['item_id']);
    $qty       = intval($_POST['quantity']);
    $type      = trim($_POST['type']);
    $remarks   = trim($_POST['remarks']);



    // ======================================================
    // VALIDATION
    // ======================================================

    if ($qty <= 0) {

        header("Location: issue.php?msg=❌ Invalid Quantity!");
        exit;
    }


    if (!in_array($type, ['IN', 'OUT'])) {

        header("Location: issue.php?msg=❌ Invalid Transaction Type!");
        exit;
    }



    try {

        $pdo->beginTransaction();



        // ======================================================
        // VALIDATE ITEM
        // ======================================================

        $stmt = $pdo->prepare("
            SELECT *
            FROM inventory_items
            WHERE id = ?
            AND school_id = ?
        ");

        $stmt->execute([
            $item_id,
            $school_id
        ]);

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


        if (!$item) {

            header("Location: issue.php?msg=❌ Invalid Item!");
            exit;
        }



        // ======================================================
        // CHECK STOCK FOR OUT
        // ======================================================

        if ($type == 'OUT') {

            if ($item['current_stock'] < $qty) {

                header("Location: issue.php?msg=❌ Insufficient Stock!");
                exit;
            }


            // Reduce Stock
            $update = $pdo->prepare("
                UPDATE inventory_items
                SET current_stock = current_stock - ?
                WHERE id = ?
                AND school_id = ?
            ");

            $update->execute([
                $qty,
                $item_id,
                $school_id
            ]);
        }



        // ======================================================
        // RETURN STOCK (IN)
        // ======================================================

        else {

            $update = $pdo->prepare("
                UPDATE inventory_items
                SET current_stock = current_stock + ?
                WHERE id = ?
                AND school_id = ?
            ");

            $update->execute([
                $qty,
                $item_id,
                $school_id
            ]);
        }



        // ======================================================
        // INSERT LOG
        // ======================================================

        $log = $pdo->prepare("
            INSERT INTO inventory_logs
            (
                school_id,
                item_id,
                quantity,
                type,
                remarks
            )
            VALUES
            (
                ?, ?, ?, ?, ?
            )
        ");

        $log->execute([
            $school_id,
            $item_id,
            $qty,
            $type,
            $remarks
        ]);


        // Audit Log
        logActivity($pdo, [
            'school_id' => $school_id,
            'user_id'   => $_SESSION['user_id'],
            'module'    => 'Inventory',
            'action'    => $type,
            'record_id' => $item_id,
            'message'   => "Inventory {$type}: {$item['name']} (Qty: {$qty})",
            'old_data'  => [
                'current_stock' => $item['current_stock']
            ],
            'new_data'  => [
                'quantity'      => $qty,
                'type'          => $type,
                'remarks'       => $remarks
            ]
        ]);

        // ======================================================
        // COMMIT
        // ======================================================

        $pdo->commit();

        $msg = "✅ Transaction Successful!";

    }

    catch (Exception $e) {

        $pdo->rollBack();

        $msg = "❌ Error Occurred!";
    }


    header("Location: issue.php?msg=" . urlencode($msg));
    exit;
}



require_once __DIR__ . '/../include/header.php';
require_once __DIR__ . '/../include/sidebar.php';



// ======================================================
// FETCH INVENTORY ITEMS
// ======================================================

$stmt = $pdo->prepare("
    SELECT *
    FROM inventory_items
    WHERE school_id = ?
    ORDER BY name ASC
");

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

$items = $stmt->fetchAll(PDO::FETCH_ASSOC);



// ======================================================
// FETCH INVENTORY LOGS
// ======================================================

$stmt = $pdo->prepare("
    SELECT
        l.*,
        i.name AS item_name
    FROM inventory_logs l
    INNER JOIN inventory_items i
        ON i.id = l.item_id
    WHERE l.school_id = ?
    ORDER BY l.id DESC
");

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

$logs = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>

<div class="content-wrapper">

    <section class="content py-4">
	<div class="mb-3 text-right">

    <a href="inventory.php" class="btn btn-primary">

        <i class="fa fa-box"></i>
        Manage Inventory

    </a>

</div>

        <div class="container-fluid">

            <?php if (isset($_GET['msg'])): ?>

                <div class="alert alert-info">

                    <?= htmlspecialchars($_GET['msg']) ?>

                </div>

            <?php endif; ?>



            <!-- Form -->

            <div class="card card-outline card-warning shadow mb-4">

                <div class="card-header">

                    <h3 class="card-title">

                        Issue / Return Item

                    </h3>

                </div>


                <div class="card-body">

                    <form method="post" class="row">

                        <input
                            type="hidden"
                            name="submit_type"
                            value="1"
                        >


                        <div class="col-md-3">

                            <select
                                name="item_id"
                                class="form-control"
                                required
                            >

                                <option value="">
                                    Select Item
                                </option>

                                <?php foreach($items as $i): ?>

                                    <option value="<?= $i['id'] ?>">

                                        <?= htmlspecialchars($i['name']) ?>
                                        (Stock: <?= $i['current_stock'] ?>)

                                    </option>

                                <?php endforeach; ?>

                            </select>

                        </div>



                        <div class="col-md-2">

                            <input
                                type="number"
                                name="quantity"
                                class="form-control"
                                placeholder="Quantity"
                                min="1"
                                required
                            >

                        </div>



                        <div class="col-md-2">

                            <select
                                name="type"
                                class="form-control"
                            >

                                <option value="OUT">

                                    Issue (OUT)

                                </option>

                                <option value="IN">

                                    Return (IN)

                                </option>

                            </select>

                        </div>



                        <div class="col-md-3">

                            <input
                                type="text"
                                name="remarks"
                                class="form-control"
                                placeholder="Issued To / Remarks"
                            >

                        </div>



                        <div class="col-md-2">

                            <button
                                type="submit"
                                class="btn btn-warning w-100"
                            >

                                Submit

                            </button>

                        </div>

                    </form>

                </div>

            </div>



            <!-- Transaction History -->

            <div class="card card-outline card-info shadow">

                <div class="card-header">

                    <h3 class="card-title">

                        Transaction History

                    </h3>

                </div>


                <div class="card-body p-0">

                    <table class="table table-bordered table-striped">

                        <thead>

                            <tr>

                                <th>#</th>

                                <th>Item</th>

                                <th>Qty</th>

                                <th>Type</th>

                                <th>Remarks</th>

                                <th>Date</th>

                            </tr>

                        </thead>


                        <tbody>

                            <?php if(count($logs) > 0): ?>

                                <?php foreach ($logs as $i => $row): ?>

                                    <tr>

                                        <td>

                                            <?= $i + 1 ?>

                                        </td>


                                        <td>

                                            <?= htmlspecialchars($row['item_name']) ?>

                                        </td>


                                        <td>

                                            <?= $row['quantity'] ?>

                                        </td>


                                        <td>

                                            <span class="badge badge-<?= $row['type'] == 'IN' ? 'success' : 'danger' ?>">

                                                <?= $row['type'] ?>

                                            </span>

                                        </td>


                                        <td>

                                            <?= htmlspecialchars($row['remarks']) ?>

                                        </td>


                                        <td>

                                            <?= date('d-m-Y h:i A', strtotime($row['created_at'])) ?>

                                        </td>

                                    </tr>

                                <?php endforeach; ?>

                            <?php else: ?>

                                <tr>

                                    <td colspan="6" class="text-center text-danger">

                                        No Transaction History Found!

                                    </td>

                                </tr>

                            <?php endif; ?>

                        </tbody>

                    </table>

                </div>

            </div>

        </div>

    </section>

</div>

<?php

require_once __DIR__ . '/../include/footer.php';

ob_end_flush();

?>