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

$page_title = 'Inventory Management';


// ======================================================
// ADD / UPDATE ITEM
// ======================================================

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

    $id              = intval($_POST['id'] ?? 0);
    $name            = trim($_POST['name']);
    $category        = trim($_POST['category']);
    $unit            = trim($_POST['unit']);
    $current_stock   = intval($_POST['current_stock']);



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

    if (empty($name)) {

        header("Location: inventory.php?msg=❌ Item Name Required!");
        exit;
    }



    // ======================================================
    // UPDATE ITEM
    // ======================================================

    if ($id > 0) {

        // Validate Item
        $check = $pdo->prepare("
            SELECT id
            FROM inventory_items
            WHERE id = ?
            AND school_id = ?
        ");

        $check->execute([
            $id,
            $school_id
        ]);

        if ($check->rowCount() == 0) {

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


        // Update Query
        $stmt = $pdo->prepare("
            UPDATE inventory_items
            SET
                name = ?,
                category = ?,
                unit = ?,
                current_stock = ?
            WHERE id = ?
            AND school_id = ?
        ");

        $stmt->execute([
            $name,
            $category,
            $unit,
            $current_stock,
            $id,
            $school_id
        ]);

        // Audit Log
        logActivity($pdo, [
            'school_id' => $school_id,
            'user_id'   => $_SESSION['user_id'],
            'module'    => 'Inventory',
            'action'    => 'UPDATE',
            'record_id' => $id,
            'message'   => "Inventory item updated: {$name}",
            'old_data'  => null,
            'new_data'  => [
                'name'            => $name,
                'category'        => $category,
                'unit'            => $unit,
                'current_stock'   => $current_stock
            ]
        ]);

        $msg = "✅ Item Updated Successfully!";
    }



    // ======================================================
    // ADD ITEM
    // ======================================================

    else {

        // Duplicate Check
        $check = $pdo->prepare("
            SELECT id
            FROM inventory_items
            WHERE school_id = ?
            AND name = ?
        ");

        $check->execute([
            $school_id,
            $name
        ]);

        if ($check->rowCount() > 0) {

            header("Location: inventory.php?msg=⚠️ Item Already Exists!");
            exit;
        }


        // Insert Query
        $stmt = $pdo->prepare("
            INSERT INTO inventory_items
            (
                school_id,
                name,
                category,
                unit,
                current_stock
            )
            VALUES
            (
                ?, ?, ?, ?, ?
            )
        ");

        $stmt->execute([
            $school_id,
            $name,
            $category,
            $unit,
            $current_stock
        ]);
// Audit Log
        logActivity($pdo, [
            'school_id' => $school_id,
            'user_id'   => $_SESSION['user_id'],
            'module'    => 'Inventory',
            'action'    => 'CREATE',
            'record_id' => $pdo->lastInsertId(),
            'message'   => "Inventory item added: {$name}",
            'old_data'  => null,
            'new_data'  => [
                'name'            => $name,
                'category'        => $category,
                'unit'            => $unit,
                'current_stock'   => $current_stock
            ]
        ]);

        $msg = "✅ Item Added Successfully!";
    }

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



// ======================================================
// DELETE ITEM
// ======================================================

if (isset($_GET['delete'])) {

    $id = intval($_GET['delete']);

    // Validate Item
    $check = $pdo->prepare("
        SELECT id
        FROM inventory_items
        WHERE id = ?
        AND school_id = ?
    ");

    $check->execute([
        $id,
        $school_id
    ]);

    if ($check->rowCount() == 0) {

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


    // Delete Query
    $stmt = $pdo->prepare("
        DELETE FROM inventory_items
        WHERE id = ?
        AND school_id = ?
    ");

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

    // Get Old Data Before Delete
    $check = $pdo->prepare("
        SELECT * FROM inventory_items
        WHERE id = ? AND school_id = ?
    ");
    $check->execute([
        $id,
        $school_id
    ]);
    $old_data = $check->fetch(PDO::FETCH_ASSOC);

    // Audit Log
    logActivity($pdo, [
        'school_id' => $school_id,
        'user_id'   => $_SESSION['user_id'],
        'module'    => 'Inventory',
        'action'    => 'DELETE',
        'record_id' => $id,
        'message'   => "Inventory item deleted: {$old_data['name']}",
        'old_data'  => $old_data,
        'new_data'  => null
    ]);

    // Delete Query
    $stmt = $pdo->prepare("
        DELETE FROM inventory_items
        WHERE id = ?
        AND school_id = ?
    ");

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

    header("Location: inventory.php?msg=🗑️ Deleted Successfully!");
    exit;
}



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



// ======================================================
// FETCH EDIT DATA
// ======================================================

$edit_data = [
    'id'              => '',
    'name'            => '',
    'category'        => '',
    'unit'            => 'pcs',
    'current_stock'   => '0'
];


if (isset($_GET['edit'])) {

    $id = intval($_GET['edit']);

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

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

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

    if ($data) {

        $edit_data = $data;
    }
}



// ======================================================
// FETCH ALL ITEMS
// ======================================================

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

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

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

?>

<div class="content-wrapper">

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

    <a href="issue.php" class="btn btn-warning">

        <i class="fa fa-exchange-alt"></i>
        Issue / Return Items

    </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-primary shadow mb-4">

                <div class="card-header">

                    <h3 class="card-title">

                        <?= $edit_data['id'] ? 'Edit' : 'Add' ?>
                        Inventory Item

                    </h3>

                </div>


                <div class="card-body">

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

                        <input
                            type="hidden"
                            name="id"
                            value="<?= $edit_data['id'] ?>"
                        >

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


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

                            <input
                                type="text"
                                name="name"
                                class="form-control"
                                value="<?= htmlspecialchars($edit_data['name']) ?>"
                                placeholder="Item Name"
                                required
                            >

                        </div>


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

                            <input
                                type="text"
                                name="category"
                                class="form-control"
                                value="<?= htmlspecialchars($edit_data['category']) ?>"
                                placeholder="Category"
                            >

                        </div>


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

                            <input
                                type="text"
                                name="unit"
                                class="form-control"
                                value="<?= htmlspecialchars($edit_data['unit']) ?>"
                                placeholder="Unit"
                            >

                        </div>


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

                            <input
                                type="number"
                                name="current_stock"
                                class="form-control"
                                value="<?= htmlspecialchars($edit_data['current_stock']) ?>"
                                placeholder="Stock"
                                required
                            >

                        </div>


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

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

                                <?= $edit_data['id'] ? 'Update' : 'Save' ?>

                            </button>

                        </div>

                    </form>

                </div>

            </div>



            <!-- Table -->

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

                <div class="card-header">

                    <h3 class="card-title">

                        Inventory List

                    </h3>

                </div>


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

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

                        <thead>

                            <tr>

                                <th>#</th>

                                <th>Name</th>

                                <th>Category</th>

                                <th>Unit</th>

                                <th>Current Stock</th>

                                <th>Minimum Stock</th>

                                <th>Actions</th>

                            </tr>

                        </thead>


                        <tbody>

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

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

                                    <tr>

                                        <td>

                                            <?= $i + 1 ?>

                                        </td>


                                        <td>

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

                                        </td>


                                        <td>

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

                                        </td>


                                        <td>

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

                                        </td>


                                        <td class="<?= ($row['current_stock'] <= $row['min_stock_level']) ? 'text-danger font-weight-bold' : '' ?>">

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

                                        </td>


                                        <td>

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

                                        </td>


                                        <td>

                                            <a
                                                href="inventory.php?edit=<?= $row['id'] ?>"
                                                class="btn btn-sm btn-success"
                                            >

                                                Edit

                                            </a>


                                            <a
                                                href="inventory.php?delete=<?= $row['id'] ?>"
                                                class="btn btn-sm btn-danger"
                                                onclick="return confirm('Are you sure?')"
                                            >

                                                Delete

                                            </a>

                                        </td>

                                    </tr>

                                <?php endforeach; ?>

                            <?php else: ?>

                                <tr>

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

                                        No Inventory Items Found!

                                    </td>

                                </tr>

                            <?php endif; ?>

                        </tbody>

                    </table>

                </div>

            </div>

        </div>

    </section>

</div>

<?php

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

ob_end_flush();

?>