<?php
require_once 'config/database.php';
require_once 'config/session.php';
require_once 'includes/header.php';

requireLogin();

$pageTitle = 'Material Management';
$action = $_GET['action'] ?? 'list';
$materialId = $_GET['id'] ?? null;

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        $pdo = getConnection();
        
        if ($action == 'add' || $action == 'edit') {
            $name = trim($_POST['name']);
            $description = trim($_POST['description']);
            $unitPrice = floatval($_POST['unit_price']);
            $stockQuantity = intval($_POST['stock_quantity']);
            
            if (empty($name) || $unitPrice < 0) {
                throw new Exception('Name is required and unit price must be non-negative');
            }
            
            if ($action == 'add') {
                $stmt = $pdo->prepare("INSERT INTO materials (name, description, unit_price, stock_quantity) VALUES (?, ?, ?, ?)");
                $stmt->execute([$name, $description, $unitPrice, $stockQuantity]);
                $_SESSION['success_message'] = 'Material added successfully!';
            } else {
                $stmt = $pdo->prepare("UPDATE materials SET name = ?, description = ?, unit_price = ?, stock_quantity = ? WHERE id = ?");
                $stmt->execute([$name, $description, $unitPrice, $stockQuantity, $materialId]);
                $_SESSION['success_message'] = 'Material updated successfully!';
            }
            
            header('Location: materials.php');
            exit();
        }
    } catch (Exception $e) {
        $_SESSION['error_message'] = $e->getMessage();
    }
}

// Handle delete action
if ($action == 'delete' && $materialId) {
    try {
        $pdo = getConnection();
        $stmt = $pdo->prepare("DELETE FROM materials WHERE id = ?");
        $stmt->execute([$materialId]);
        $_SESSION['success_message'] = 'Material deleted successfully!';
        header('Location: materials.php');
        exit();
    } catch (Exception $e) {
        $_SESSION['error_message'] = 'Cannot delete material. It may be referenced in quotations or invoices.';
    }
}

// Get material data for editing
$material = null;
if ($action == 'edit' && $materialId) {
    try {
        $pdo = getConnection();
        $stmt = $pdo->prepare("SELECT * FROM materials WHERE id = ?");
        $stmt->execute([$materialId]);
        $material = $stmt->fetch();
        if (!$material) {
            $_SESSION['error_message'] = 'Material not found';
            header('Location: materials.php');
            exit();
        }
    } catch (Exception $e) {
        $_SESSION['error_message'] = 'Error loading material data';
        header('Location: materials.php');
        exit();
    }
}

// Get all materials for listing
$materials = [];
$search = $_GET['search'] ?? '';
try {
    $pdo = getConnection();
    if ($search) {
        $stmt = $pdo->prepare("SELECT * FROM materials WHERE name LIKE ? OR description LIKE ? ORDER BY name");
        $searchTerm = "%$search%";
        $stmt->execute([$searchTerm, $searchTerm]);
    } else {
        $stmt = $pdo->query("SELECT * FROM materials ORDER BY name");
    }
    $materials = $stmt->fetchAll();
} catch (Exception $e) {
    $_SESSION['error_message'] = 'Error loading materials';
}
?>

<div class="container-fluid py-4">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1 class="h3 mb-0">
                    <i class="fas fa-boxes"></i> Material Management
                </h1>
                <?php if ($action == 'list'): ?>
                    <a href="materials.php?action=add" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Add Material
                    </a>
                <?php else: ?>
                    <a href="materials.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Back to List
                    </a>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <?php if ($action == 'list'): ?>
        <!-- Material List -->
        <div class="row">
            <div class="col-12">
                <div class="card shadow">
                    <div class="card-header py-3">
                        <div class="row align-items-center">
                            <div class="col">
                                <h6 class="m-0 font-weight-bold text-primary">All Materials</h6>
                            </div>
                            <div class="col-auto">
                                <form method="GET" class="d-flex">
                                    <input type="hidden" name="action" value="list">
                                    <input type="text" class="form-control me-2" name="search" 
                                           placeholder="Search materials..." value="<?php echo htmlspecialchars($search); ?>">
                                    <button type="submit" class="btn btn-outline-primary">
                                        <i class="fas fa-search"></i>
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <?php if (empty($materials)): ?>
                            <div class="text-center py-4">
                                <i class="fas fa-boxes fa-3x text-muted mb-3"></i>
                                <p class="text-muted">No materials found.</p>
                                <a href="materials.php?action=add" class="btn btn-primary">
                                    <i class="fas fa-plus"></i> Add First Material
                                </a>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>Name</th>
                                            <th>Description</th>
                                            <th>Unit Price</th>
                                            <th>Stock Quantity</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($materials as $material): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($material['name']); ?></td>
                                            <td><?php echo htmlspecialchars($material['description']); ?></td>
                                            <td>₹<?php echo number_format($material['unit_price'], 2); ?></td>
                                            <td>
                                                <span class="badge bg-<?php echo $material['stock_quantity'] > 10 ? 'success' : ($material['stock_quantity'] > 0 ? 'warning' : 'danger'); ?>">
                                                    <?php echo $material['stock_quantity']; ?>
                                                </span>
                                            </td>
                                            <td>
                                                <a href="materials.php?action=edit&id=<?php echo $material['id']; ?>" 
                                                   class="btn btn-sm btn-outline-primary">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <a href="materials.php?action=delete&id=<?php echo $material['id']; ?>" 
                                                   class="btn btn-sm btn-outline-danger"
                                                   onclick="return confirm('Are you sure you want to delete this material?')">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        
    <?php elseif ($action == 'add' || $action == 'edit'): ?>
        <!-- Add/Edit Material Form -->
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card shadow">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">
                            <i class="fas fa-<?php echo $action == 'add' ? 'plus' : 'edit'; ?>"></i>
                            <?php echo $action == 'add' ? 'Add New Material' : 'Edit Material'; ?>
                        </h6>
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="name" class="form-label">Material Name *</label>
                                    <input type="text" class="form-control" id="name" name="name" 
                                           value="<?php echo htmlspecialchars($material['name'] ?? ''); ?>" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="unit_price" class="form-label">Unit Price (₹) *</label>
                                    <input type="number" class="form-control" id="unit_price" name="unit_price" 
                                           step="0.01" min="0" value="<?php echo $material['unit_price'] ?? ''; ?>" required>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="stock_quantity" class="form-label">Stock Quantity</label>
                                    <input type="number" class="form-control" id="stock_quantity" name="stock_quantity" 
                                           min="0" value="<?php echo $material['stock_quantity'] ?? '0'; ?>">
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="description" class="form-label">Description</label>
                                <textarea class="form-control" id="description" name="description" rows="3"><?php echo htmlspecialchars($material['description'] ?? ''); ?></textarea>
                            </div>
                            
                            <div class="d-flex justify-content-end">
                                <a href="materials.php" class="btn btn-secondary me-2">Cancel</a>
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save"></i> 
                                    <?php echo $action == 'add' ? 'Add Material' : 'Update Material'; ?>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

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