<?php
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
include('includes/db.php');
include('includes/header.php');

// ---------------- CSRF Token ----------------
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

// ---------------- ROLE CHECK ----------------
$user_role = $_SESSION['user_role'] ?? '';
if (!in_array($user_role, ['Admin','Super_admin','Pharmacist'])) {
    die("Access denied.");
}

// ---------------- FACILITY ----------------
$facilityId = (int)($_SESSION['facility_id'] ?? 0);
if ($facilityId <= 0) {
    die("Facility not assigned.");
}

// ---------------- Fetch Products (Drug & Consumable only, Facility-specific) ----------------
$stmt = $pdo->prepare("
    SELECT id, name, category_type, status
    FROM products
    WHERE category_type IN ('drug','consumable')
      AND facility_id = ?
    ORDER BY name ASC
");
$stmt->execute([$facilityId]);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ---------------- Handle Stock IN (Add/Edit) ----------------
if (isset($_POST['add_stock']) && hash_equals($csrf, $_POST['csrf'])) {

    $product_id      = (int) $_POST['product_id'];
    $quantity        = (int) $_POST['quantity'];
    $expiration_date = !empty($_POST['expiration_date']) ? $_POST['expiration_date'] : null;
    $note            = trim($_POST['note']);
    $edit_id         = isset($_POST['edit_id']) ? (int)$_POST['edit_id'] : 0;

    if ($quantity <= 0) {
        $_SESSION['flash'] = [
            'message' => 'Quantity must be greater than zero.',
            'color'   => '#dc3545'
        ];
        header("Location: medical_inventory.php");
        exit;
    }

    // Only Admin / Super_admin can Edit
    if ($edit_id > 0 && !in_array($user_role, ['Admin','Super_admin'])) {
        $_SESSION['flash'] = [
            'message' => 'You do not have permission to edit stock.',
            'color'   => '#dc3545'
        ];
        header("Location: medical_inventory.php");
        exit;
    }

    // ================= EDIT STOCK =================
    if ($edit_id > 0) {
        $stmtCheck = $pdo->prepare("
            SELECT stock_in, stock_out
            FROM stock
            WHERE id = ? AND facility_id = ?
        ");
        $stmtCheck->execute([$edit_id, $facilityId]);
        $row = $stmtCheck->fetch(PDO::FETCH_ASSOC);

        if ($row) {
            if ($quantity < $row['stock_out']) {
                $_SESSION['flash'] = [
                    'message' => 'Stock in cannot be less than stock already used.',
                    'color'   => '#dc3545'
                ];
            } else {
                $stmtUpdate = $pdo->prepare("
                    UPDATE stock SET
                        stock_in = ?,
                        expiration_date = ?,
                        note = ?
                    WHERE id = ? AND facility_id = ?
                ");
                $stmtUpdate->execute([
                    $quantity,
                    $expiration_date,
                    $note,
                    $edit_id,
                    $facilityId
                ]);

                $_SESSION['flash'] = [
                    'message' => 'Stock updated successfully. Remaining adjusted automatically.',
                    'color'   => '#28a745'
                ];
            }
        }
    } else {
        // ================= ADD / RESTORE STOCK =================
        // By default, new stock is disabled; oldest stock of the product remains enabled
        $stmtInsert = $pdo->prepare("
            INSERT INTO stock
                (product_id, stock_in, stock_out, expiration_date, note, status, facility_id, created_at)
            VALUES
                (?, ?, 0, ?, ?, 'disabled', ?, NOW())
        ");
        $stmtInsert->execute([
            $product_id,
            $quantity,
            $expiration_date,
            $note,
            $facilityId
        ]);

        // Check if there is any enabled stock for this product
        $stmtEnabled = $pdo->prepare("
            SELECT COUNT(*) 
            FROM stock 
            WHERE product_id = ? AND status = 'enabled' AND facility_id = ?
        ");
        $stmtEnabled->execute([$product_id, $facilityId]);
        $enabledCount = (int)$stmtEnabled->fetchColumn();

        // If no enabled stock, enable the oldest one
        if ($enabledCount === 0) {
            $pdo->prepare("
                UPDATE stock 
                SET status = 'enabled' 
                WHERE product_id = ? AND facility_id = ?
                ORDER BY created_at ASC
                LIMIT 1
            ")->execute([$product_id, $facilityId]);
        }

        $_SESSION['flash'] = [
            'message' => "Stock added successfully. Quantity: $quantity",
            'color'   => '#28a745'
        ];
    }

    header("Location: medical_inventory.php");
    exit;
}

// ---------------- Handle Stock Enable/Disable ----------------
if (isset($_GET['toggle_status']) && is_numeric($_GET['toggle_status'])) {

    // Only Admin and Super_admin can toggle
    if (!in_array($user_role, ['Admin','Super_admin'])) {
        $_SESSION['flash'] = [
            'message' => 'You do not have permission to change stock status.',
            'color' => '#dc3545'
        ];
        header("Location: medical_inventory.php");
        exit;
    }

    $id = (int) $_GET['toggle_status'];

    $stmt = $pdo->prepare("SELECT status, product_id FROM stock WHERE id = ? AND facility_id = ?");
    $stmt->execute([$id, $facilityId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($row) {
        $new_status = $row['status'] === 'enabled' ? 'disabled' : 'enabled';
        // Allow toggle only if FIFO rules allow
        if ($new_status === 'enabled') {
            // Check if any other stock of the same product is enabled
            $stmtOther = $pdo->prepare("
                SELECT COUNT(*) FROM stock 
                WHERE product_id = ? AND status='enabled' AND id != ? AND facility_id = ?
            ");
            $stmtOther->execute([$row['product_id'], $id, $facilityId]);
            $countOther = (int)$stmtOther->fetchColumn();
            if ($countOther > 0) {
                $_SESSION['flash'] = [
                    'message' => "Cannot enable this stock while older stock is still active.",
                    'color'   => '#ffc107'
                ];
                header("Location: medical_inventory.php");
                exit;
            }
        }

        $pdo->prepare("UPDATE stock SET status = ? WHERE id = ? AND facility_id = ?")
            ->execute([$new_status, $id, $facilityId]);

        $_SESSION['flash'] = [
            'message' => "Stock entry marked as $new_status",
            'color'   => $new_status === 'enabled' ? '#28a745' : '#ffc107'
        ];
    }

    header("Location: medical_inventory.php");
    exit;
}

// ---------------- Fetch Stock IN Entries (LATEST FIRST) ----------------
$stockEntries = $pdo->prepare("
    SELECT
        s.id,
        s.product_id,
        s.stock_in,
        s.stock_out,
        s.expiration_date,
        s.note,
        s.status,
        s.created_at,
        p.name AS product_name,
        p.category_type
    FROM stock s
    JOIN products p ON p.id = s.product_id
    WHERE s.facility_id = ?
    ORDER BY s.created_at DESC
");
$stockEntries->execute([$facilityId]);
$stockEntries = $stockEntries->fetchAll(PDO::FETCH_ASSOC);

// ---------------- Prepare per-product alert states ----------------
$alertButtons = [];
foreach ($products as $p) {
    if ($p['status'] !== 'enabled') continue;
    $stmt = $pdo->prepare("
        SELECT stock_in, stock_out, expiration_date
        FROM stock
        WHERE product_id = ? AND status = 'enabled' AND facility_id = ?
        ORDER BY created_at DESC
        LIMIT 1
    ");
    $stmt->execute([$p['id'], $facilityId]);
    $lastStock = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$lastStock) continue;
    $remaining = $lastStock['stock_in'] - $lastStock['stock_out'];
    if ($remaining <= 0) continue;
    $daysToExpiry = null;
    if (!empty($lastStock['expiration_date'])) {
        $diffDays = ceil((strtotime($lastStock['expiration_date']) - time()) / 86400);
        if ($diffDays >= 0 && $diffDays <= 30) $daysToExpiry = $diffDays;
    }
    if ($remaining <= 15 || $daysToExpiry !== null) {
        $alertButtons[] = [
            'product_name' => $p['name'],
            'remaining'    => $remaining,
            'days'         => $daysToExpiry,
            'expiry'       => $lastStock['expiration_date']
        ];
    }
}
?>


<!-- HTML -->
<nav class="header-navbar navbar navbar-with-menu navbar-fixed-top navbar-semi-dark navbar-shadow">
    <?php include('includes/navbar.php'); ?>
</nav>

<div class="main-menu menu-fixed menu-dark menu-accordion menu-shadow">
    <?php include('includes/sidebar.php'); ?>
</div>

<div class="app-content content container-fluid">
<div class="content-wrapper">
<div class="card">

<div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
    <h4 class="card-title">Medical Inventory Management</h4>

    <div class="d-flex gap-2 flex-wrap">
        <?php if (in_array($user_role, ['Admin','Super_admin','Pharmacist'])): ?>
        <button class="btn btn-outline-primary" onclick="openAddModal();">
            <i class="icon-plus-circle"></i> Add Stock In
        </button>
        <?php else: ?>
        <button class="btn btn-outline-primary" disabled>
            <i class="icon-plus-circle"></i> Add Stock In
        </button>
        <?php endif; ?>

        <!-- COMBINED ALERT BUTTONS -->
        <?php foreach ($alertButtons as $alert): ?>
            <button class="btn btn-danger btn-sm"
                onclick="openAlertModal(
                    'Stock Alert',
                    '<?= htmlspecialchars($alert['product_name']) ?>',
                    'Remaining: <?= $alert['remaining'] ?><?= $alert['days'] !== null ? ' | Expires in '.$alert['days'].' days' : '' ?>',
                    '<?= $alert['expiry'] ?: '-' ?>'
                )">
                <?= htmlspecialchars($alert['product_name']) ?>
                [<?= $alert['remaining'] ?> Qty remain]<?= $alert['days'] !== null ? ' | '.$alert['days'].' Days remain' : '' ?>
            </button>
        <?php endforeach; ?>
    </div>
</div>

<div class="card-body">
<div class="table-responsive">

<table class="table table-hover" id="Table">
<thead>
<tr>
    <th>#</th>
    <th>Product</th>
    <th>Stock In</th>
    <th>Stock Out</th>
    <th>Remaining</th>
    <th>Expiration Date</th>
    <!--<th>Note</th>-->
    <th>Status</th>
    <th>Date Added</th>
    <th>Actions</th>
</tr>
</thead>

<tbody>
<?php
$total = count($stockEntries);
foreach ($stockEntries as $index => $s):

    $remaining = $s['stock_in'] - $s['stock_out'];
    $expired   = $s['expiration_date'] && strtotime($s['expiration_date']) < time();

    // ----------------- Auto-disable finished stock -----------------
    if ($remaining <= 0 && $s['status'] === 'enabled') {
        $pdo->prepare("UPDATE stock SET status='disabled' WHERE id=? AND facility_id=?")
            ->execute([$s['id'], $facilityId]);
        $s['status'] = 'disabled';
    }

    $daysToExpiry = '-';
    if ($s['expiration_date']) {
        $diff = ceil((strtotime($s['expiration_date']) - time()) / 86400);
        if ($diff >= 0 && $diff <= 30) {
            $daysToExpiry = $diff . ' Days Remain';
        }
    }

    $rowStyle = '';
    if ($expired) {
        $rowStyle = 'background:#f8d7da;';
    } elseif ($remaining <= 0 || $s['status'] === 'disabled') {
        $rowStyle = 'background:#e2e3e5;';
    }

    // Admin / Super_admin can always edit
    $canEdit = in_array($user_role, ['Admin','Super_admin']);

    // STRICT toggle rules for enable/disable
    $canToggle = in_array($user_role, ['Admin','Super_admin']);

    $num = $total - $index;

    // Check if there is older stock (FIFO) with remaining qty AND not expired
    $stmtOlder = $pdo->prepare("
        SELECT COUNT(*) FROM stock
        WHERE product_id=? 
          AND id != ? 
          AND facility_id=? 
          AND (stock_in-stock_out) > 0
          AND (expiration_date IS NULL OR expiration_date >= NOW())
          AND status='enabled'
    ");
    $stmtOlder->execute([$s['product_id'], $s['id'], $facilityId]);
    $olderCount = (int)$stmtOlder->fetchColumn();
?>
<tr style="<?= $rowStyle ?>">
    <td><?= $num ?></td>

    <td>
        <?= htmlspecialchars($s['product_name']) ?>
        (<?= ucfirst($s['category_type']) ?>)
        <?php if ($s['status'] === 'disabled' && $olderCount > 0 && $remaining > 0): ?>
            <br><small class="text-warning">Waiting for older stock to finish or expire</small>
        <?php elseif ($remaining <= 0): ?>
            <br><small class="text-secondary">Stock finished</small>
        <?php endif; ?>
        <?php if ($expired): ?>
            <br><small class="text-danger">Expired</small>
        <?php endif; ?>
    </td>

    <td class="text-success"><?= (int)$s['stock_in'] ?></td>
    <td class="text-danger"><?= (int)$s['stock_out'] ?></td>
    <td><?= $remaining ?></td>

    <td>
        <div><?= $s['expiration_date'] ?: '-' ?></div>
        <div class="btn btn-sm btn-secondary"><?= $daysToExpiry ?></div>
    </td>

    <td>
        <strong style="color:
            <?= $expired ? '#dc3545' : ($s['status']=='enabled' ? '#28a745' : '#ffc107') ?>">
            <?= $expired ? 'Expired' : ucfirst($s['status']) ?>
        </strong>
    </td>

    <td><?= date('Y-m-d H:i', strtotime($s['created_at'])) ?></td>

    <td>
        <button class="btn btn-sm btn-info"
            <?= $canEdit
                ? "onclick=\"openEditModal(
                    {$s['id']},
                    {$s['stock_in']},
                    '{$s['expiration_date']}',
                    '".addslashes($s['note'])."',
                    {$s['product_id']}
                )\""
                : 'disabled'
            ?>>
            Edit
        </button>

        <?php if ($canToggle): ?>
            <a href="?toggle_status=<?= $s['id'] ?>"
               class="btn btn-sm <?= $s['status']=='enabled' ? 'btn-warning' : 'btn-success' ?>">
                <?= $s['status']=='enabled' ? 'Disable' : 'Enable' ?>
            </a>
        <?php else: ?>
            <button class="btn btn-sm btn-secondary" disabled>
                <?= $s['status']=='enabled' ? 'Disable' : 'Enable' ?>
            </button>
        <?php endif; ?>
    </td>
</tr>
<?php endforeach; ?>
</tbody>


</table>


</div>
</div>
</div>
</div>
</div>


<!-- ADD / EDIT MODAL -->
<div id="stockModal" class="modal-custom" style="display:none;">
<div class="modal-content-custom">

<div class="modal-header-custom">
    <h4 id="modalTitle">Add Stock In</h4>
    <span class="close-custom"
        onclick="document.getElementById('stockModal').style.display='none'">&times;</span>
</div>

<form method="post">
<input type="hidden" name="csrf" value="<?= $csrf ?>">
<input type="hidden" name="edit_id" id="edit_id" value="0">

<div class="modal-body-custom">

<div class="form-group">
    <label>Product</label>
    <select name="product_id" class="form-control" id="productSelect" required>
        <option value="">-- Select Product --</option>
        <?php foreach ($products as $p): ?>
            <option value="<?= $p['id'] ?>">
                <?= htmlspecialchars($p['name']) ?> (<?= ucfirst($p['category_type']) ?>)
            </option>
        <?php endforeach; ?>
    </select>
</div>

<div class="form-group">
    <label>Quantity</label>
    <input type="number" name="quantity" min="0"
        class="form-control" id="quantity" required>
</div>

<div class="form-group">
    <label>Expiration Date</label>
    <input type="date" name="expiration_date"
        class="form-control" id="expiration_date">
</div>

<div class="form-group">
    <label>Note</label>
    <textarea name="note" class="form-control"
        rows="2" id="note"></textarea>
</div>

</div>

<div class="modal-footer-custom">
    <button type="submit" name="add_stock" class="btn btn-primary">Save</button>
    <button type="button" class="btn btn-secondary"
        onclick="document.getElementById('stockModal').style.display='none'">
        Close
    </button>
</div>
</form>
</div>
</div>

<!-- ALERT MODAL -->
<div id="alertModal" class="modal-custom" style="display:none;">
<div class="modal-content-custom">

<div class="modal-header-custom">
    <h4 id="alertTitle"></h4>
    <span class="close-custom"
        onclick="document.getElementById('alertModal').style.display='none'">&times;</span>
</div>

<div class="modal-body-custom">
    <p><strong>Product:</strong> <span id="alertProduct"></span></p>
    <p><strong>Info:</strong> <span id="alertInfo"></span></p>
    <p><strong>Expiration:</strong> <span id="alertExpiry"></span></p>
</div>

<div class="modal-footer-custom">
    <button type="button" class="btn btn-secondary"
        onclick="document.getElementById('alertModal').style.display='none'">
        Close
    </button>
</div>

</div>
</div>

<style>
.modal-custom{position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:1050}
.modal-content-custom{background:#fff;width:420px;margin:8% auto;padding:20px;border-radius:6px}
.modal-header-custom{display:flex;justify-content:space-between;align-items:center}
.close-custom{font-size:24px;cursor:pointer}
.toast-message{position:fixed;top:20px;right:20px;padding:12px 18px;color:#fff;border-radius:5px;z-index:9999}
</style>

<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0/dist/css/select2.min.css" rel="stylesheet" />

<script>
document.addEventListener('DOMContentLoaded', function () {

    $('#productSelect').select2({ width: '100%' });

    function showToast(msg, color) {
        let t = document.createElement('div');
        t.className = 'toast-message';
        t.style.background = color;
        t.innerText = msg;
        document.body.appendChild(t);
        setTimeout(() => t.remove(), 4000);
    }

    <?php if (isset($_SESSION['flash'])): ?>
        showToast(
            '<?= $_SESSION['flash']['message'] ?>',
            '<?= $_SESSION['flash']['color'] ?>'
        );
        <?php unset($_SESSION['flash']); ?>
    <?php endif; ?>
});

function openEditModal(id, quantity, expiration, note, product_id) {
    document.getElementById('modalTitle').innerText = 'Edit Stock';
    document.getElementById('edit_id').value = id;
    document.getElementById('quantity').value = quantity;
    document.getElementById('expiration_date').value = expiration;
    document.getElementById('note').value = note;
    $('#productSelect').val(product_id).trigger('change');
    document.getElementById('stockModal').style.display = 'block';
}

function openAddModal() {
    document.getElementById('modalTitle').innerText = 'Add Stock In';
    document.getElementById('edit_id').value = 0;
    document.getElementById('quantity').value = '';
    document.getElementById('expiration_date').value = '';
    document.getElementById('note').value = '';
    $('#productSelect').val('').trigger('change');
    document.getElementById('stockModal').style.display = 'block';
}

function openAlertModal(title, product, info, expiry) {
    document.getElementById('alertTitle').innerText = title;
    document.getElementById('alertProduct').innerText = product;
    document.getElementById('alertInfo').innerText = info;
    document.getElementById('alertExpiry').innerText = expiry;
    document.getElementById('alertModal').style.display = 'block';
}
</script>

<?php include('includes/footer.php'); ?>

