<?php
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 to access this page";
    header('Location: dashboard.php');
    exit;
}

$current_user = $auth->getCurrentUser();

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    if ($action === 'delete' && ($auth->hasRole('super_admin') || $auth->hasPermission('can_delete'))) {
        $id = (int)$_POST['id'];
        
        try {
            $material = $db->fetchOne("SELECT images FROM `building_materials` WHERE id = ?", [$id]);
            
            if ($material && $material['images']) {
                $images = json_decode($material['images'], true);
                foreach ($images as $image) {
                    $file_path = MATERIAL_UPLOAD_DIR . '/' . basename($image);
                    if (file_exists($file_path)) {
                        unlink($file_path);
                    }
                }
            }
            
            $sql = "DELETE FROM `building_materials` WHERE id = ?";
            $db->execute($sql, [$id]);
            
            $_SESSION['success'] = "Material deleted successfully";
            header('Location: materials.php');
            exit;
        } catch (Exception $e) {
            $_SESSION['error'] = "Failed to delete material";
        }
    }
}

// Get filter parameters
$search = $_GET['search'] ?? '';
$category_filter = $_GET['category'] ?? '';
$status_filter = $_GET['status'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

// Build query
$where = [];
$params = [];

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

if ($category_filter) {
    $where[] = "category = ?";
    $params[] = $category_filter;
}

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

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

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

$sql = "SELECT m.*, u.first_name, u.last_name
        FROM `building_materials` m
        LEFT JOIN users u ON m.created_by = u.id
        $where_sql
        ORDER BY m.created_at DESC
        LIMIT $limit OFFSET $offset";

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

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">Building Materials</li>
        </ol>
    </nav>
</div>

<?php if (isset($_SESSION['success'])): ?>
<div class="alert alert-success alert-dismissible fade show">
    <i class="fas fa-check-circle"></i> <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">
            <i class="fas fa-boxes"></i> All Materials
            <span class="badge bg-primary"><?php echo number_format($total); ?></span>
        </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">
                    <div class="input-group">
                        <span class="input-group-text"><i class="fas fa-search"></i></span>
                        <input type="text" name="search" class="form-control" placeholder="Search..." 
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                </div>
                
                <div class="col-md-3">
                    <select name="category" class="form-select">
                        <option value="">All Categories</option>
                        <option value="cement" <?php echo $category_filter === 'cement' ? 'selected' : ''; ?>>Cement</option>
                        <option value="blocks" <?php echo $category_filter === 'blocks' ? 'selected' : ''; ?>>Blocks</option>
                        <option value="roofing" <?php echo $category_filter === 'roofing' ? 'selected' : ''; ?>>Roofing</option>
                        <option value="tiles" <?php echo $category_filter === 'tiles' ? 'selected' : ''; ?>>Tiles</option>
                        <option value="paint" <?php echo $category_filter === 'paint' ? 'selected' : ''; ?>>Paint</option>
                        <option value="plumbing" <?php echo $category_filter === 'plumbing' ? 'selected' : ''; ?>>Plumbing</option>
                        <option value="electrical" <?php echo $category_filter === 'electrical' ? 'selected' : ''; ?>>Electrical</option>
                    </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>
                        <option value="inactive" <?php echo $status_filter === 'inactive' ? 'selected' : ''; ?>>Inactive</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>
        
        <!-- Materials Table -->
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Image</th>
                        <th>Name</th>
                        <th>Category</th>
                        <th>Price</th>
                        <th>Unit</th>
                        <th>Stock</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($materials)): ?>
                    <tr>
                        <td colspan="8" 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>
                                <br>
                                <small class="text-muted"><?php echo htmlspecialchars(substr($material['description'], 0, 50)); ?>...</small>
                            </td>
                            <td><span class="badge bg-info"><?php echo ucfirst($material['category']); ?></span></td>
                            <td><strong>₦<?php echo number_format($material['price'], 2); ?></strong></td>
                            <td><?php echo htmlspecialchars($material['unit']); ?></td>
                            <td><?php echo number_format($material['stock_quantity']); ?></td>
                            <td>
                                <?php
                                $badge_class = [
                                    'available' => 'success',
                                    'out_of_stock' => 'danger',
                                    'inactive' => '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">
                                    <?php if ($auth->hasPermission('can_edit') || $auth->hasRole('super_admin')): ?>
                                    <a href="material-form.php?id=<?php echo $material['id']; ?>" 
                                       class="btn btn-outline-success">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <?php endif; ?>
                                    
                                    <?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>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <nav>
            <ul class="pagination justify-content-center">
                <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>">Previous</a>
                </li>
                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>"><?php echo $i; ?></a>
                </li>
                <?php endfor; ?>
                <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>">Next</a>
                </li>
            </ul>
        </nav>
        <?php endif; ?>
    </div>
</div>

<form method="POST" id="deleteForm" style="display: none;">
    <input type="hidden" name="action" value="delete">
    <input type="hidden" name="id" id="deleteId">
    <input type="hidden" name="csrf_token" value="<?php echo Security::generateCSRFToken(); ?>">
</form>

<script>
    $('.delete-btn').click(function() {
        const id = $(this).data('id');
        const name = $(this).data('name');
        
        Swal.fire({
            title: 'Delete Material?',
            html: `Delete <strong>${name}</strong>?<br><br>This action cannot be undone!`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                $('#deleteId').val(id);
                $('#deleteForm').submit();
            }
        });
    });
</script>

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