<?php
// ==========================================
// FILE: admin/materials.php
// ==========================================
/* Similar structure to lands.php but for building materials */
define('ROVO_APP', true);
require_once '../config.php';
require_once '../Auth.php';

$page_title = 'Building Materials';

if (!$auth->hasPermission('can_manage_properties') && !$auth->hasRole('super_admin')) {
    $_SESSION['error'] = "You don't have permission";
    header('Location: dashboard.php');
    exit;
}

// Filters
$search = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? '';
$category_filter = $_GET['category'] ?? '';
$page_num = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 15;
$offset = ($page_num - 1) * $limit;

$where = [];
$params = [];

if ($search) {
    $where[] = "(name LIKE ? OR description LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($status_filter) {
    $where[] = "bm.status = ?";
    $params[] = $status_filter;
}

if ($category_filter) {
    $where[] = "bm.category_id = ?";
    $params[] = $category_filter;
}

$where_sql = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';

$count_sql = "SELECT COUNT(*) as total FROM building_materials bm $where_sql";
$total = $db->fetchOne($count_sql, $params)['total'];
$total_pages = ceil($total / $limit);

$sql = "SELECT bm.*, c.name as category_name
        FROM building_materials bm
        LEFT JOIN categories c ON bm.category_id = c.id
        $where_sql
        ORDER BY bm.created_at DESC
        LIMIT $limit OFFSET $offset";

$materials = $db->fetchAll($sql, $params);

// Get categories
$categories = $db->fetchAll("SELECT * FROM categories WHERE type = 'material' AND status = 'active'");

include 'includes/header.php';
?>

<div class="page-header">
    <h1>Building Materials</h1>
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
            <li class="breadcrumb-item active">Materials</li>
        </ol>
    </nav>
</div>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="fas fa-tools"></i> All Materials</h5>
        <?php if ($auth->hasPermission('can_create') || $auth->hasRole('super_admin')): ?>
        <a href="material-form.php" class="btn btn-primary">
            <i class="fas fa-plus"></i> Add New Material
        </a>
        <?php endif; ?>
    </div>
    
    <div class="card-body">
        <!-- Filters -->
        <form method="GET" class="mb-4">
            <div class="row g-3">
                <div class="col-md-4">
                    <input type="text" name="search" class="form-control" placeholder="Search..." 
                           value="<?php echo htmlspecialchars($search); ?>">
                </div>
                <div class="col-md-3">
                    <select name="category" class="form-select">
                        <option value="">All Categories</option>
                        <?php foreach ($categories as $cat): ?>
                        <option value="<?php echo $cat['id']; ?>" <?php echo $category_filter == $cat['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($cat['name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <select name="status" class="form-select">
                        <option value="">All Status</option>
                        <option value="available" <?php echo $status_filter === 'available' ? 'selected' : ''; ?>>Available</option>
                        <option value="out_of_stock" <?php echo $status_filter === 'out_of_stock' ? 'selected' : ''; ?>>Out of Stock</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-filter"></i> Filter
                    </button>
                </div>
            </div>
        </form>
        
        <!-- Table -->
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Image</th>
                        <th>Name</th>
                        <th>Category</th>
                        <th>Price/Unit</th>
                        <th>Stock</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($materials)): ?>
                    <tr>
                        <td colspan="7" class="text-center py-4">
                            <i class="fas fa-inbox fa-3x text-muted mb-3 d-block"></i>
                            <p class="text-muted">No materials found</p>
                        </td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($materials as $material): ?>
                        <tr>
                            <td>
                                <?php 
                                $images = json_decode($material['images'], true);
                                $first_image = $images[0] ?? 'placeholder.jpg';
                                ?>
                                <img src="../<?php echo htmlspecialchars($first_image); ?>" 
                                     alt="Material" class="rounded" style="width: 60px; height: 60px; object-fit: cover;">
                            </td>
                            <td>
                                <strong><?php echo htmlspecialchars($material['name']); ?></strong>
                                <?php if ($material['featured']): ?>
                                <span class="badge bg-warning text-dark ms-1">Featured</span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo htmlspecialchars($material['category_name'] ?? 'N/A'); ?></td>
                            <td>
                                <strong>₦<?php echo number_format($material['price']); ?></strong>
                                <small class="text-muted">/ <?php echo htmlspecialchars($material['unit']); ?></small>
                            </td>
                            <td>
                                <?php if ($material['stock_quantity'] > 0): ?>
                                <span class="badge bg-success"><?php echo number_format($material['stock_quantity']); ?></span>
                                <?php else: ?>
                                <span class="badge bg-danger">Out of Stock</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php
                                $badge_class = [
                                    'available' => 'success',
                                    'out_of_stock' => 'danger',
                                    'discontinued' => 'secondary'
                                ][$material['status']] ?? 'secondary';
                                ?>
                                <span class="badge bg-<?php echo $badge_class; ?>">
                                    <?php echo ucfirst(str_replace('_', ' ', $material['status'])); ?>
                                </span>
                            </td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <a href="material-form.php?id=<?php echo $material['id']; ?>" 
                                       class="btn btn-outline-success" data-bs-toggle="tooltip" title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    
                                    <?php if ($auth->hasPermission('can_delete') || $auth->hasRole('super_admin')): ?>
                                    <button type="button" class="btn btn-outline-danger delete-btn" 
                                            data-id="<?php echo $material['id']; ?>"
                                            data-name="<?php echo htmlspecialchars($material['name']); ?>">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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