<?php
// modules/suppliers/index.php
session_start();
require_once '../../../pharmacy/modules/assets/db_connect.php';
require_once '../../../pharmacy/modules/includes/header.php';
require_once '../../../pharmacy/modules/includes/sidebar.php';

// role guard: only admin
if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'admin') {
    echo "<div class='col-md-10 ml-sm-auto px-4 py-4'><div class='alert alert-danger'>Access denied.</div></div>";
    require_once '../../../pharmacy/modules/includes/footer.php';
    exit;
}

// search & pagination
$search = trim($_GET['q'] ?? '');
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 12;
$offset = ($page - 1) * $perPage;

$sqlWhere = '';
$params = [];
if ($search !== '') {
    $sqlWhere = "WHERE name LIKE ? OR contact LIKE ? OR email LIKE ?";
    $like = "%{$search}%";
    $params = [$like, $like, $like];
}

// total count
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM suppliers $sqlWhere");
$countStmt->execute($params);
$total = $countStmt->fetchColumn();
$pages = max(1, ceil($total / $perPage));

// fetch page
$query = "SELECT * FROM suppliers $sqlWhere ORDER BY name LIMIT ? OFFSET ?";
$stmt = $pdo->prepare($query);
$execParams = array_merge($params, [$perPage, $offset]);
$stmt->execute($execParams);
$suppliers = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="col-md-10 ml-sm-auto px-4 py-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h3 class="text-success">Suppliers</h3>
        <a href="../../../pharmacy/modules/suppliers/add_supplier.php" class="btn btn-primary">+ Add Supplier</a>
    </div>

    <form class="form-inline mb-3" method="GET" action="">
        <input type="text" name="q" value="<?= htmlspecialchars($search) ?>" class="form-control mr-2" placeholder="Search name, contact, email">
        <button class="btn btn-outline-secondary">Search</button>
    </form>

    <div class="table-responsive">
        <table class="table table-bordered table-hover">
            <thead class="thead-light">
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Contact</th>
                    <th>Email</th>
                    <th>Address</th>
                    <th>Created At</th>
                    <th style="width:150px">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (count($suppliers) === 0): ?>
                    <tr><td colspan="7" class="text-center">No suppliers found.</td></tr>
                <?php else: ?>
                    <?php foreach ($suppliers as $s): ?>
                        <tr id="row-<?= $s['id'] ?>">
                            <td><?= $s['id'] ?></td>
                            <td><?= htmlspecialchars($s['name']) ?></td>
                            <td><?= htmlspecialchars($s['contact'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($s['email'] ?? '-') ?></td>
                            <td style="max-width:250px;white-space:pre-wrap;"><?= htmlspecialchars($s['address'] ?? '-') ?></td>
                            <td><?= date('d-M-Y H:i', strtotime($s['created_at'])) ?></td>
                            <td>
                            <?php if($_SESSION['user']['role']=='admin'){?>
                                <a href="../../../pharmacy/modules/suppliers/edit_supplier.php?id=<?= $s['id'] ?>" class="btn btn-sm btn-warning">Edit</a>
							
                                <form method="POST" action="../../../pharmacy/modules/suppliers/delete_supplier.php" style="display:inline;" onsubmit="return confirm('Delete supplier? This will fail if supplier has purchases or batches.')">
                                    <input type="hidden" name="id" value="<?= $s['id'] ?>">
                                    <button class="btn btn-sm btn-danger">Delete</button>
                                </form>
                                <?php 
							}
							else
							{
								echo"";
								}
								?>
                                
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- pagination -->
    <nav aria-label="Page navigation">
      <ul class="pagination">
        <?php for ($p = 1; $p <= $pages; $p++): ?>
            <li class="page-item <?= $p === $page ? 'active' : '' ?>">
                <a class="page-link" href="../../../pharmacy2/modules/suppliers/?q=<?= urlencode($search) ?>&amp;page=<?= $p ?>"><?= $p ?></a>
            </li>
        <?php endfor; ?>
      </ul>
    </nav>
</div>

<?php require_once '../../../pharmacy/modules/includes/footer.php'; ?>
