<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'CHIEF_PHARMACIST', 'PHARMACIST'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

// Get suppliers
$search_term = isset($_GET['search']) ? $_GET['search'] : '';
$filter_rating = isset($_GET['rating']) ? $_GET['rating'] : '';

$where_clauses = ["is_active = 1"];

if ($search_term) {
    $search_term = $conn->real_escape_string($search_term);
    $where_clauses[] = "(supplier_name LIKE '%$search_term%' OR supplier_code LIKE '%$search_term%' OR contact_person LIKE '%$search_term%')";
}

if ($filter_rating) {
    $where_clauses[] = "rating = '" . $conn->real_escape_string($filter_rating) . "'";
}

$where_sql = implode(' AND ', $where_clauses);

$suppliers_sql = "SELECT * FROM pharmacy_suppliers 
                  WHERE $where_sql
                  ORDER BY supplier_name ASC";
$suppliers = $conn->query($suppliers_sql);

// Get statistics
$stats_sql = "SELECT 
                COUNT(*) as total_suppliers,
                SUM(CASE WHEN rating = 'EXCELLENT' THEN 1 ELSE 0 END) as excellent_count,
                SUM(CASE WHEN rating = 'GOOD' THEN 1 ELSE 0 END) as good_count
              FROM pharmacy_suppliers
              WHERE is_active = 1";
$stats = $conn->query($stats_sql)->fetch_assoc();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Suppliers')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet">
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Suppliers</h4>
                                <div class="page-title-right">
                                    <a href="pharmacy_supplier_add.php" class="btn btn-primary">
                                        <i class="ri-add-line me-1"></i>Add Supplier
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics -->
                    <div class="row mb-4">
                        <div class="col-xl-4 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-muted mb-2">Total Suppliers</p>
                                            <h4 class="mb-0"><?php echo $stats['total_suppliers']; ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-primary rounded fs-3">
                                                <i class="ri-truck-line text-primary"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-4 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-muted mb-2">Excellent Rated</p>
                                            <h4 class="mb-0"><?php echo $stats['excellent_count']; ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-success rounded fs-3">
                                                <i class="ri-star-line text-success"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-4 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-muted mb-2">Good Rated</p>
                                            <h4 class="mb-0"><?php echo $stats['good_count']; ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-info rounded fs-3">
                                                <i class="ri-thumb-up-line text-info"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <form method="GET" action="" class="row g-3">
                                        <div class="col-md-6">
                                            <label class="form-label">Search</label>
                                            <input type="text" class="form-control" name="search" 
                                                   value="<?php echo htmlspecialchars($search_term); ?>"
                                                   placeholder="Search by name, code, or contact person...">
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Rating</label>
                                            <select class="form-control" name="rating">
                                                <option value="">All Ratings</option>
                                                <option value="EXCELLENT" <?php echo $filter_rating == 'EXCELLENT' ? 'selected' : ''; ?>>Excellent</option>
                                                <option value="GOOD" <?php echo $filter_rating == 'GOOD' ? 'selected' : ''; ?>>Good</option>
                                                <option value="FAIR" <?php echo $filter_rating == 'FAIR' ? 'selected' : ''; ?>>Fair</option>
                                                <option value="POOR" <?php echo $filter_rating == 'POOR' ? 'selected' : ''; ?>>Poor</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2 d-flex align-items-end">
                                            <button type="submit" class="btn btn-primary w-100">
                                                <i class="ri-search-line me-1"></i>Search
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Suppliers List -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table id="suppliersTable" class="table table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Code</th>
                                                    <th>Supplier Name</th>
                                                    <th>Contact Person</th>
                                                    <th>Phone</th>
                                                    <th>Email</th>
                                                    <th>Rating</th>
                                                    <th>Payment Terms</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($supplier = $suppliers->fetch_assoc()): ?>
                                                    <tr>
                                                        <td><strong><?php echo htmlspecialchars($supplier['supplier_code']); ?></strong></td>
                                                        <td><?php echo htmlspecialchars($supplier['supplier_name']); ?></td>
                                                        <td><?php echo htmlspecialchars($supplier['contact_person'] ?: '-'); ?></td>
                                                        <td><?php echo htmlspecialchars($supplier['phone_primary']); ?></td>
                                                        <td><?php echo htmlspecialchars($supplier['email'] ?: '-'); ?></td>
                                                        <td>
                                                            <?php
                                                            $rating_class = 'badge-primary';
                                                            if ($supplier['rating'] == 'EXCELLENT') $rating_class = 'badge-success';
                                                            elseif ($supplier['rating'] == 'GOOD') $rating_class = 'badge-info';
                                                            elseif ($supplier['rating'] == 'FAIR') $rating_class = 'badge-warning';
                                                            elseif ($supplier['rating'] == 'POOR') $rating_class = 'badge-danger';
                                                            ?>
                                                            <span class="badge <?php echo $rating_class; ?>">
                                                                <?php echo $supplier['rating']; ?>
                                                            </span>
                                                        </td>
                                                        <td><?php echo htmlspecialchars($supplier['payment_terms'] ?: '-'); ?></td>
                                                        <td>
                                                            <div class="dropdown">
                                                                <button class="btn btn-sm btn-soft-secondary dropdown-toggle" 
                                                                        type="button" data-bs-toggle="dropdown">
                                                                    Actions
                                                                </button>
                                                                <ul class="dropdown-menu">
                                                                    <li>
                                                                        <a class="dropdown-item" href="pharmacy_supplier_view.php?id=<?php echo $supplier['supplier_id']; ?>">
                                                                            <i class="ri-eye-line me-2"></i>View Details
                                                                        </a>
                                                                    </li>
                                                                    <li>
                                                                        <a class="dropdown-item" href="pharmacy_supplier_edit.php?id=<?php echo $supplier['supplier_id']; ?>">
                                                                            <i class="ri-edit-line me-2"></i>Edit
                                                                        </a>
                                                                    </li>
                                                                    <li><hr class="dropdown-divider"></li>
                                                                    <li>
                                                                        <a class="dropdown-item text-danger" href="#" 
                                                                           onclick="deactivateSupplier(<?php echo $supplier['supplier_id']; ?>)">
                                                                            <i class="ri-close-circle-line me-2"></i>Deactivate
                                                                        </a>
                                                                    </li>
                                                                </ul>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    </div>
        </div>

        <?php include 'layouts/footer.php'; ?>
    </div>
</div>

<?php include 'layouts/vendor-scripts.php'; ?>
<script src="assets/libs/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="assets/libs/datatables.net-bs5/js/dataTables.bootstrap5.min.js"></script>
<script src="assets/js/app.js"></script>

<script>
$(document).ready(function() {
    $('#suppliersTable').DataTable({
        pageLength: 25,
        order: [[1, 'asc']]
    });
});

function deactivateSupplier(supplierId) {
    if (confirm('Are you sure you want to deactivate this supplier?')) {
        window.location.href = 'pharmacy_supplier_deactivate.php?id=' + supplierId;
    }
}
</script>
</body>
</html>