<?php
define('ROVO_APP', true);
require_once '../config.php';
require_once '../Auth.php';

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

$current_user = $auth->getCurrentUser();
$is_edit = isset($_GET['id']);
$material = null;

if ($is_edit) {
    $id = (int)$_GET['id'];
    $material = $db->fetchOne("SELECT * FROM building_materials WHERE id = ?", [$id]);
    
    if (!$material) {
        $_SESSION['error'] = "Material not found";
        header('Location: materials.php');
        exit;
    }
    
    $page_title = 'Edit Material';
} else {
    $page_title = 'Add New Material';
}

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

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
    $name = trim($_POST['name']);
    $category_id = !empty($_POST['category_id']) ? (int)$_POST['category_id'] : null;
    $description = trim($_POST['description']);
    $price = !empty($_POST['price']) ? (float)$_POST['price'] : null;
    $unit = trim($_POST['unit']);
    $stock_quantity = !empty($_POST['stock_quantity']) ? (int)$_POST['stock_quantity'] : 0;
    $min_order_quantity = !empty($_POST['min_order_quantity']) ? (int)$_POST['min_order_quantity'] : 1;
    $supplier_name = trim($_POST['supplier_name']);
    $supplier_contact = trim($_POST['supplier_contact']);
    $status = $_POST['status'];
    $featured = isset($_POST['featured']) ? 1 : 0;
    
    // Specifications
    $specifications = [];
    if (!empty($_POST['spec_keys']) && !empty($_POST['spec_values'])) {
        foreach ($_POST['spec_keys'] as $index => $key) {
            if (!empty($key) && !empty($_POST['spec_values'][$index])) {
                $specifications[$key] = $_POST['spec_values'][$index];
            }
        }
    }
    
    if (empty($name)) $errors[] = "Material name is required";
    if (empty($unit)) $errors[] = "Unit is required";
    
    // Handle images
    $images = [];
    $existing_images = $is_edit ? json_decode($material['images'], true) ?? [] : [];
    
    if (!empty($_FILES['images']['name'][0])) {
        foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name) {
            if ($_FILES['images']['error'][$key] === UPLOAD_ERR_OK) {
                $file_name = $_FILES['images']['name'][$key];
                $file_size = $_FILES['images']['size'][$key];
                $file_tmp = $_FILES['images']['tmp_name'][$key];
                $file_type = $_FILES['images']['type'][$key];
                
                if (!in_array($file_type, ALLOWED_IMAGE_TYPES)) {
                    $errors[] = "Invalid image type: $file_name";
                    continue;
                }
                
                if ($file_size > MAX_FILE_SIZE) {
                    $errors[] = "File too large: $file_name";
                    continue;
                }
                
                $extension = pathinfo($file_name, PATHINFO_EXTENSION);
                $new_filename = 'material_' . uniqid() . '_' . time() . '.' . $extension;
                $upload_path = MATERIAL_UPLOAD_DIR . '/' . $new_filename;
                
                if (move_uploaded_file($file_tmp, $upload_path)) {
                    $images[] = 'uploads/materials/' . $new_filename;
                }
            }
        }
    }
    
    if ($is_edit) {
        $images = array_merge($existing_images, $images);
    }
    
    if (empty($images) && !$is_edit) {
        $errors[] = "At least one material image is required";
    }
    
    if (empty($errors)) {
        try {
            $slug = Security::generateSlug($name);
            
            $slug_check = $db->fetchOne("SELECT id FROM building_materials WHERE slug = ? AND id != ?", [$slug, $id ?? 0]);
            if ($slug_check) {
                $slug .= '-' . time();
            }
            
            if ($is_edit) {
                $sql = "UPDATE building_materials SET 
                        name = ?, slug = ?, category_id = ?, description = ?,
                        price = ?, unit = ?, stock_quantity = ?, min_order_quantity = ?,
                        specifications = ?, supplier_name = ?, supplier_contact = ?,
                        images = ?, status = ?, featured = ?, updated_at = NOW()
                        WHERE id = ?";
                
                $db->execute($sql, [
                    $name, $slug, $category_id, $description,
                    $price, $unit, $stock_quantity, $min_order_quantity,
                    json_encode($specifications), $supplier_name, $supplier_contact,
                    json_encode($images), $status, $featured, $id
                ]);
                
                $_SESSION['success'] = "Material updated successfully";
            } else {
                $sql = "INSERT INTO building_materials (
                        name, slug, category_id, description, price, unit,
                        stock_quantity, min_order_quantity, specifications,
                        supplier_name, supplier_contact, images, status, featured, created_by
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                
                $db->execute($sql, [
                    $name, $slug, $category_id, $description, $price, $unit,
                    $stock_quantity, $min_order_quantity, json_encode($specifications),
                    $supplier_name, $supplier_contact, json_encode($images),
                    $status, $featured, $current_user['id']
                ]);
                
                $_SESSION['success'] = "Material added successfully";
            }
            
            header('Location: materials.php');
            exit;
            
        } catch (Exception $e) {
            $errors[] = "Database error: " . $e->getMessage();
        }
    }
}

include 'includes/header.php';
?>

<div class="page-header">
    <h1><?php echo $page_title; ?></h1>
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
            <li class="breadcrumb-item"><a href="materials.php">Materials</a></li>
            <li class="breadcrumb-item active"><?php echo $is_edit ? 'Edit' : 'Add New'; ?></li>
        </ol>
    </nav>
</div>

<?php if (!empty($errors)): ?>
<div class="alert alert-danger alert-dismissible fade show">
    <ul class="mb-0">
        <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
        <?php endforeach; ?>
    </ul>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<form method="POST" enctype="multipart/form-data">
    <input type="hidden" name="csrf_token" value="<?php echo Security::generateCSRFToken(); ?>">
    
    <div class="row">
        <div class="col-lg-8">
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Material Information</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Material Name <span class="text-danger">*</span></label>
                        <input type="text" name="name" class="form-control" required
                               value="<?php echo htmlspecialchars($material['name'] ?? ''); ?>"
                               placeholder="e.g., Dangote Cement 50kg">
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Category</label>
                            <select name="category_id" class="form-select">
                                <option value="">Select Category</option>
                                <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo $cat['id']; ?>"
                                        <?php echo ($material['category_id'] ?? '') == $cat['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($cat['name']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Unit <span class="text-danger">*</span></label>
                            <input type="text" name="unit" class="form-control" required
                                   value="<?php echo htmlspecialchars($material['unit'] ?? ''); ?>"
                                   placeholder="e.g., bag, ton, piece">
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea name="description" class="form-control" rows="4"
                                  placeholder="Describe the material..."><?php echo htmlspecialchars($material['description'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Price (₦)</label>
                            <input type="number" name="price" class="form-control" min="0" step="0.01"
                                   value="<?php echo $material['price'] ?? ''; ?>">
                        </div>
                        
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Stock Quantity</label>
                            <input type="number" name="stock_quantity" class="form-control" min="0"
                                   value="<?php echo $material['stock_quantity'] ?? 0; ?>">
                        </div>
                        
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Min Order Qty</label>
                            <input type="number" name="min_order_quantity" class="form-control" min="1"
                                   value="<?php echo $material['min_order_quantity'] ?? 1; ?>">
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Specifications -->
            <div class="card mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Specifications</h5>
                    <button type="button" class="btn btn-sm btn-primary" id="addSpec">
                        <i class="fas fa-plus"></i> Add Specification
                    </button>
                </div>
                <div class="card-body">
                    <div id="specificationsContainer">
                        <?php 
                        $specs = $is_edit ? json_decode($material['specifications'], true) ?? [] : [];
                        if (!empty($specs)):
                            foreach ($specs as $key => $value):
                        ?>
                        <div class="row mb-2 spec-row">
                            <div class="col-md-5">
                                <input type="text" name="spec_keys[]" class="form-control" placeholder="Name"
                                       value="<?php echo htmlspecialchars($key); ?>">
                            </div>
                            <div class="col-md-6">
                                <input type="text" name="spec_values[]" class="form-control" placeholder="Value"
                                       value="<?php echo htmlspecialchars($value); ?>">
                            </div>
                            <div class="col-md-1">
                                <button type="button" class="btn btn-danger btn-sm remove-spec">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </div>
                        <?php endforeach; endif; ?>
                    </div>
                </div>
            </div>
            
            <!-- Supplier Info -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Supplier Information</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Supplier Name</label>
                            <input type="text" name="supplier_name" class="form-control"
                                   value="<?php echo htmlspecialchars($material['supplier_name'] ?? ''); ?>">
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Supplier Contact</label>
                            <input type="text" name="supplier_contact" class="form-control"
                                   value="<?php echo htmlspecialchars($material['supplier_contact'] ?? ''); ?>">
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Images -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Material Images</h5>
                </div>
                <div class="card-body">
                    <div class="image-upload-container" id="imageUploadArea">
                        <i class="fas fa-cloud-upload-alt upload-icon"></i>
                        <h5>Drag and drop images here</h5>
                        <p class="text-muted">or click to browse</p>
                        <input type="file" name="images[]" id="imageInput" multiple accept="image/*" style="display: none;">
                    </div>
                    
                    <div class="image-preview-container" id="imagePreview">
                        <?php if ($is_edit && !empty($material['images'])): ?>
                            <?php foreach (json_decode($material['images'], true) as $image): ?>
                            <div class="image-preview">
                                <img src="../<?php echo htmlspecialchars($image); ?>" alt="Material">
                            </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-lg-4">
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Publish</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select">
                            <option value="available" <?php echo ($material['status'] ?? 'available') === 'available' ? 'selected' : ''; ?>>Available</option>
                            <option value="out_of_stock" <?php echo ($material['status'] ?? '') === 'out_of_stock' ? 'selected' : ''; ?>>Out of Stock</option>
                            <option value="discontinued" <?php echo ($material['status'] ?? '') === 'discontinued' ? 'selected' : ''; ?>>Discontinued</option>
                            <option value="inactive" <?php echo ($material['status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                        </select>
                    </div>
                    
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" name="featured" id="featured"
                               <?php echo ($material['featured'] ?? 0) ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="featured">
                            Featured Material
                        </label>
                    </div>
                    
                    <button type="submit" name="submit" class="btn btn-primary w-100">
                        <i class="fas fa-save"></i> <?php echo $is_edit ? 'Update' : 'Publish'; ?>
                    </button>
                    
                    <a href="materials.php" class="btn btn-outline-secondary w-100 mt-2">
                        <i class="fas fa-times"></i> Cancel
                    </a>
                </div>
            </div>
        </div>
    </div>
</form>

<style>
    .image-upload-container {
        border: 3px dashed #ddd;
        border-radius: 15px;
        padding: 40px;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s;
        background: #f8f9fa;
    }
    
    .image-upload-container:hover,
    .image-upload-container.dragover {
        border-color: var(--primary);
        background: rgba(212, 160, 23, 0.05);
    }
    
    .upload-icon {
        font-size: 3rem;
        color: #ddd;
        margin-bottom: 15px;
    }
    
    .image-preview-container {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
        gap: 15px;
        margin-top: 20px;
    }
    
    .image-preview {
        position: relative;
        border-radius: 10px;
        overflow: hidden;
        aspect-ratio: 1;
    }
    
    .image-preview img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    
    .image-preview .remove-image {
        position: absolute;
        top: 5px;
        right: 5px;
        background: rgba(255, 0, 0, 0.8);
        color: white;
        border: none;
        border-radius: 50%;
        width: 30px;
        height: 30px;
        cursor: pointer;
    }
</style>



<script>
   
    // Add specification
    $('#addSpec').click(function() {
        const specRow = `
            <div class="row mb-2 spec-row">
                <div class="col-md-5">
                    <input type="text" name="spec_keys[]" class="form-control" placeholder="Name (e.g., Weight)">
                </div>
                <div class="col-md-6">
                    <input type="text" name="spec_values[]" class="form-control" placeholder="Value (e.g., 50kg)">
                </div>
                <div class="col-md-1">
                    <button type="button" class="btn btn-danger btn-sm remove-spec">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        `;
        $('#specificationsContainer').append(specRow);
    });
    
    $(document).on('click', '.remove-spec', function() {
        $(this).closest('.spec-row').remove();
    });
    
    // Image upload
    const uploadArea = document.getElementById('imageUploadArea');
    const imageInput = document.getElementById('imageInput');
    const imagePreview = document.getElementById('imagePreview');
    let uploadedFiles = [];
    
    uploadArea.addEventListener('click', function(e) {
        if (!e.target.closest('.remove-image')) {
            imageInput.click();
        }
    });
    
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        uploadArea.addEventListener(eventName, e => {
            e.preventDefault();
            e.stopPropagation();
        });
    });
    
    ['dragenter', 'dragover'].forEach(eventName => {
        uploadArea.addEventListener(eventName, () => uploadArea.classList.add('dragover'));
    });
    
    ['dragleave', 'drop'].forEach(eventName => {
        uploadArea.addEventListener(eventName', () => uploadArea.classList.remove('dragover'));
    });
    
    uploadArea.addEventListener('drop', function(e) {
        handleFiles(e.dataTransfer.files);
    });
    
    imageInput.addEventListener('change', function() {
        handleFiles(this.files);
    });
    
    function handleFiles(files) {
        Array.from(files).forEach(file => {
            if (!file.type.startsWith('image/')) {
                Swal.fire('Error', 'Please upload only images', 'error');
                return;
            }
            if (file.size > 5242880) {
                Swal.fire('Error', 'File size must be less than 5MB', 'error');
                return;
            }
            uploadedFiles.push(file);
            previewFile(file);
        });
        updateFileInput();
    }
    
    function previewFile(file) {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onloadend = function() {
            const index = uploadedFiles.indexOf(file);
            const preview = document.createElement('div');
            preview.className = 'image-preview';
            preview.innerHTML = `
                <img src="${reader.result}" alt="Preview">
                <button type="button" class="remove-image" data-index="${index}">
                    <i class="fas fa-times"></i>
                </button>
            `;
            imagePreview.appendChild(preview);
            
            preview.querySelector('.remove-image').addEventListener('click', function(e) {
                e.stopPropagation();
                const idx = parseInt(this.dataset.index);
                uploadedFiles.splice(idx, 1);
                preview.remove();
                updateFileInput();
                document.querySelectorAll('.remove-image').forEach((btn, i) => {
                    btn.dataset.index = i;
                });
            });
        };
    }
    
    function updateFileInput() {
        if (uploadedFiles.length > 0) {
            const dataTransfer = new DataTransfer();
            uploadedFiles.forEach(file => dataTransfer.items.add(file));
            imageInput.files = dataTransfer.files;
        }
    }


</script>

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