Mini Kabibi Habibi

Current Path : C:/xampp/htdocs/clinic/
Upload File :
Current File : C:/xampp/htdocs/clinic/issue_supplies.php

<?php
session_start();
include 'includes/db.php';

// Access control
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: login.php");
    exit();
}

$page_title = "Issue Medical Supply";
$success_message = $_SESSION['success_message'] ?? '';
unset($_SESSION['success_message']);

$error_message = '';

// Fetch supplies with available balance and not expired
$today = date('Y-m-d');
$supply_stmt = $pdo->prepare("SELECT id, item, balance, expiration_date, date_received FROM medical_supplies WHERE balance > 0 AND expiration_date >= ? ORDER BY item ASC");
$supply_stmt->execute([$today]);
$supply_options = $supply_stmt->fetchAll(PDO::FETCH_ASSOC);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $date = $_POST['date'] ?? '';
    $patient_name = trim($_POST['patient_name'] ?? '');
    $age = intval($_POST['age'] ?? 0);
    $school = trim($_POST['school'] ?? '');
    $supply_id = intval($_POST['supply_id'] ?? 0);
    $quantity = intval($_POST['quantity'] ?? 0);
    $released_by = trim($_POST['released_by'] ?? '');
    $received_by = trim($_POST['received_by'] ?? '');
    $remarks = trim($_POST['remarks'] ?? '');

    if ($date && $patient_name && $age > 0 && $school && $supply_id > 0 && $quantity > 0 && $released_by && $received_by && $remarks) {
        // Check stock availability
        $stmt = $pdo->prepare("SELECT item, balance FROM medical_supplies WHERE id = :id");
        $stmt->execute([':id' => $supply_id]);
        $supply = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($supply && $supply['balance'] >= $quantity) {
            $pdo->beginTransaction();
            try {
                // Insert issuance record
                $insert = $pdo->prepare("INSERT INTO supply_issuance 
                    (`date`, patient_name, age, school, supply_name, quantity, released_by, received_by, remarks)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $insert->execute([
                    $date,
                    $patient_name,
                    $age,
                    $school,
                    $supply['item'],
                    $quantity,
                    $released_by,
                    $received_by,
                    $remarks
                ]);

                // Update medical supplies
                $update = $pdo->prepare("UPDATE medical_supplies SET issued = issued + ?, balance = balance - ? WHERE id = ?");
                $update->execute([$quantity, $quantity, $supply_id]);

                $pdo->commit();

                $_SESSION['success_message'] = "Supply successfully issued.";
                header("Location: " . basename(__FILE__));
                exit();
            } catch (Exception $e) {
                $pdo->rollBack();
                $error_message = "Transaction failed: " . $e->getMessage();
            }
        } else {
            $error_message = "Not enough stock available to issue.";
        }
    } else {
        $error_message = "Please fill out all required fields correctly.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title><?= htmlspecialchars($page_title) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" />
    <style>
        body {
            margin: 0;
            background-color: #f8f9fa;
        }
        .sidebar {
            position: fixed;
            top: 0;
            left: 0;
            width: 250px;
            height: 100vh;
            background-color: #2c3e50;
            color: white;
            overflow-y: auto;
        }
        .sidebar a {
            color: #ccc;
            text-decoration: none;
            padding: 15px;
            display: block;
            transition: 0.3s;
        }
        .sidebar a:hover {
            background-color: #34495e;
            color: #fff;
        }
        .sidebar .collapse a {
            font-size: 0.95rem;
            padding-left: 30px;
        }
        .main-content {
            margin-left: 250px;
            padding: 40px;
            box-sizing: border-box;
            min-height: 100vh;
        }
        h2.page-title {
            font-weight: 600;
            margin-bottom: 30px;
        }
    </style>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
</head>
<body>

<?php include 'sidebar.php'; ?>

<div class="main-content">
    <h2 class="page-title"><?= htmlspecialchars($page_title) ?></h2>

    <?php if ($success_message): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success_message) ?></div>
    <?php elseif ($error_message): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error_message) ?></div>
    <?php endif; ?>

    <button type="button" class="btn btn-success mb-4" data-bs-toggle="modal" data-bs-target="#issueSupplyModal">
        Issue Here
    </button>
</div>

<!-- Modal -->
<div class="modal fade <?= $error_message ? 'show' : '' ?>" id="issueSupplyModal" tabindex="-1" aria-labelledby="issueSupplyModalLabel" aria-hidden="<?= $error_message ? 'false' : 'true' ?>" style="<?= $error_message ? 'display: block;' : '' ?>">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header bg-light">
        <h5 class="modal-title">Issue Medical Supply</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body">
        <form id="issueSupplyForm" class="needs-validation" novalidate method="POST" action="<?= basename(__FILE__) ?>">
          <div class="row g-3">
            <div class="col-md-3 mb-3">
              <label for="date" class="form-label">Date <span class="text-danger">*</span></label>
              <input type="date" name="date" id="date" class="form-control" required value="<?= htmlspecialchars($_POST['date'] ?? date('Y-m-d')) ?>">
              <div class="invalid-feedback">Please select the date.</div>
            </div>

            <div class="col-md-3 mb-3">
              <label for="patient_name" class="form-label">Name of Patient <span class="text-danger">*</span></label>
              <input type="text" name="patient_name" id="patient_name" class="form-control" required value="<?= htmlspecialchars($_POST['patient_name'] ?? '') ?>">
              <div class="invalid-feedback">Please enter the patient's name.</div>
            </div>

            <div class="col-md-2 mb-3">
              <label for="age" class="form-label">Age <span class="text-danger">*</span></label>
              <input type="number" name="age" id="age" class="form-control" min="1" required value="<?= htmlspecialchars($_POST['age'] ?? '') ?>">
              <div class="invalid-feedback">Please enter a valid age.</div>
            </div>

            <div class="col-md-4 mb-3">
              <label for="school" class="form-label">School <span class="text-danger">*</span></label>
              <input type="text" name="school" id="school" class="form-control" required value="<?= htmlspecialchars($_POST['school'] ?? '') ?>">
              <div class="invalid-feedback">Please enter the school name.</div>
            </div>

            <div class="col-md-4 mb-3">
              <label for="supply_id" class="form-label">Medical Supplies <span class="text-danger">*</span></label>
              <select name="supply_id" id="supply_id" class="form-select" required>
                <option value="">-- Select Supply --</option>
                <?php foreach ($supply_options as $s): ?>
                  <option value="<?= $s['id'] ?>" <?= (isset($_POST['supply_id']) && $_POST['supply_id'] == $s['id']) ? 'selected' : '' ?>>
                    <?= htmlspecialchars($s['item']) ?> (Available: <?= $s['balance'] ?>, Received: <?= date('M d, Y', strtotime($s['date_received'])) ?>)
                  </option>
                <?php endforeach; ?>
              </select>
              <div class="invalid-feedback">Please select a medical supply.</div>
            </div>

            <div class="col-md-2 mb-3">
              <label for="quantity" class="form-label">Quantity <span class="text-danger">*</span></label>
              <input type="number" name="quantity" id="quantity" class="form-control" min="1" required value="<?= htmlspecialchars($_POST['quantity'] ?? '') ?>">
              <div class="invalid-feedback">Please enter a valid quantity.</div>
            </div>

            <div class="col-md-3 mb-3">
              <label for="released_by" class="form-label">Released by <span class="text-danger">*</span></label>
              <input type="text" name="released_by" id="released_by" class="form-control" required value="<?= htmlspecialchars($_POST['released_by'] ?? '') ?>">
              <div class="invalid-feedback">Please enter who released the supply.</div>
            </div>

            <div class="col-md-3 mb-3">
              <label for="received_by" class="form-label">Received by <span class="text-danger">*</span></label>
              <input type="text" name="received_by" id="received_by" class="form-control" required value="<?= htmlspecialchars($_POST['received_by'] ?? '') ?>">
              <div class="invalid-feedback">Please enter who received the supply.</div>
            </div>

            <div class="col-md-12 mb-3">
              <label for="remarks" class="form-label">Remarks <span class="text-danger">*</span></label>
              <textarea name="remarks" id="remarks" class="form-control" rows="2" required><?= htmlspecialchars($_POST['remarks'] ?? '') ?></textarea>
              <div class="invalid-feedback">Please enter remarks.</div>
            </div>
          </div>

          <div class="modal-footer">
            <button type="submit" class="btn btn-success">Issue Supply</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
  (() => {
    'use strict';
    const form = document.getElementById('issueSupplyForm');

    form.addEventListener('submit', (event) => {
      if (!form.checkValidity()) {
        event.preventDefault();
        event.stopPropagation();
      }
      form.classList.add('was-validated');
    });

    <?php if ($error_message): ?>
      document.addEventListener("DOMContentLoaded", () => {
        const modal = new bootstrap.Modal(document.getElementById('issueSupplyModal'));
        modal.show();
      });
    <?php endif; ?>
  })();
</script>

</body>
</html>