<?php
$title = 'Edit Building Asset';
$active = 'buildings';
require_once __DIR__ . '/../layouts/header.php';
require_once __DIR__ . '/../layouts/sidebar.php';

$errors = Session::get('errors', []);
Session::remove('errors');

// Document types for the dropdown
$documentTypes = [
    'award_letter' => 'Award Letter',
    'completion_letter' => 'Completion Letter',
    'floor_plan' => 'Floor Plan/Design',
    'inspection_report' => 'Verification/Inspector Report',
    'pictures' => 'Upload Pictures'
];
?>

<div class="container-fluid">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-content">
            <h1>
                <i class="fas fa-edit"></i>
                Edit Building Asset: <?php echo Security::escape($asset['building_name']); ?>
            </h1>
            <p>Update building asset information</p>
        </div>
        
       <div class="header-actions">
    <a href="<?php echo BASE_URL; ?>/buildings/show/<?php echo $asset['id']; ?>" class="btn btn-success">
        <i class="fas fa-eye"></i> View Details
    </a>
    <a href="<?php echo BASE_URL; ?>/buildings" class="btn btn-secondary">
        <i class="fas fa-arrow-left"></i> Back to List
    </a>
</div>
    </div>
    
<!-- Success Message Display (ADD THIS SECTION) -->
<?php
$successMessage = Session::get('success', '');
if (!empty($successMessage)):
?>
<div class="alert alert-success alert-dismissible fade show" role="alert" id="successAlert">
    <i class="fas fa-check-circle"></i>
    <?php echo Security::escape($successMessage); ?>
    <button type="button" class="btn-close" onclick="this.parentElement.style.display='none'">&times;</button>
</div>
<?php 
    Session::remove('success');
endif; 
?>

<?php
$errorMessage = Session::get('error', '');
if (!empty($errorMessage)):
?>
<div class="alert alert-danger alert-dismissible fade show" role="alert" id="errorAlert">
    <i class="fas fa-exclamation-circle"></i>
    <?php echo Security::escape($errorMessage); ?>
    <button type="button" class="btn-close" onclick="this.parentElement.style.display='none'">&times;</button>
</div>
<?php 
    Session::remove('error');
endif; 
?>

<!-- Add Loading Message Here -->
<div id="loadingMessage" style="display: none; margin-bottom: 20px;">
    <div class="alert alert-info">
        <i class="fas fa-spinner fa-spin"></i>
        <span id="loadingText">Processing your request...</span>
    </div>
</div>

    <!-- Form -->
    <div class="form-section">
        <form method="POST" action="<?php echo BASE_URL; ?>/buildings/update/<?php echo $asset['id']; ?>" 
              enctype="multipart/form-data" id="buildingForm">
            <?php echo Security::csrfField(); ?>
            
            <!-- Basic Information -->
            <div class="form-section-inner">
                <div class="section-title">
                    <h3><i class="fas fa-info-circle"></i> Basic Information</h3>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label>Asset Code</label>
                        <input type="text" value="<?php echo Security::escape($asset['asset_code']); ?>" 
                               class="form-control" readonly disabled>
                    </div>
                    
                    <div class="form-group">
                        <label class="required">Ownership Type</label>
                        <select name="ownership_type" id="ownership_type" required 
                                class="form-control <?php echo isset($errors['ownership_type']) ? 'error' : ''; ?>">
                            <option value="">Select Ownership Type</option>
                            <option value="FGN" <?php echo ($asset['ownership_type'] ?? '') == 'FGN' ? 'selected' : ''; ?>>FGN (NIS)</option>
                            <option value="State" <?php echo ($asset['ownership_type'] ?? '') == 'State' ? 'selected' : ''; ?>>State</option>
                            <option value="Private" <?php echo ($asset['ownership_type'] ?? '') == 'Private' ? 'selected' : ''; ?>>Private</option>
                        </select>
                        <?php if (isset($errors['ownership_type'])): ?>
                            <small class="error-text"><?php echo $errors['ownership_type']; ?></small>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="required">Building Name</label>
                        <input type="text" name="building_name" value="<?php echo Security::escape($asset['building_name']); ?>" 
                               required maxlength="255" class="form-control <?php echo isset($errors['building_name']) ? 'error' : ''; ?>">
                        <?php if (isset($errors['building_name'])): ?>
                            <small class="error-text"><?php echo $errors['building_name']; ?></small>
                        <?php endif; ?>
                    </div>
                    
                    <div class="form-group">
                        <label class="required">Building Type</label>
                        <select name="building_type" id="building_type" required 
                                class="form-control <?php echo isset($errors['building_type']) ? 'error' : ''; ?>">
                            <option value="">Select Type</option>
                            <option value="Office" <?php echo $asset['building_type'] == 'Office' ? 'selected' : ''; ?>>Office</option>
                            <option value="Residential" <?php echo $asset['building_type'] == 'Residential' ? 'selected' : ''; ?>>Residential</option>
                            <option value="Warehouse" <?php echo $asset['building_type'] == 'Warehouse' ? 'selected' : ''; ?>>Warehouse</option>
                            <option value="Barracks" <?php echo $asset['building_type'] == 'Barracks' ? 'selected' : ''; ?>>Barracks</option>
                            <option value="Training Facility" <?php echo $asset['building_type'] == 'Training Facility' ? 'selected' : ''; ?>>Training Facility</option>
                            <option value="Medical Center" <?php echo $asset['building_type'] == 'Medical Center' ? 'selected' : ''; ?>>Medical Center</option>
                            <option value="Other">Other</option>
                        </select>
                        <?php if (isset($errors['building_type'])): ?>
                            <small class="error-text"><?php echo $errors['building_type']; ?></small>
                        <?php endif; ?>
                    </div>
                </div>
                
                       <div class="form-row">
                    <div class="form-group">
                        <label class="required">Purpose / Function</label>
                        <select name="purpose_function" id="purpose_function" required 
                                class="form-control <?php echo isset($errors['purpose_function']) ? 'error' : ''; ?>">
                            <option value="">Select Purpose/Function</option>
                            <option value="Command / Formation" <?php echo ($asset['purpose_function'] ?? '') == 'Command / Formation' ? 'selected' : ''; ?>>Command / Formation</option>
                            <option value="Area Office" <?php echo ($asset['purpose_function'] ?? '') == 'Area Office' ? 'selected' : ''; ?>>Area Office</option>
                            <option value="Divisional Office" <?php echo ($asset['purpose_function'] ?? '') == 'Divisional Office' ? 'selected' : ''; ?>>Divisional Office</option>
                            <option value="PPT Office" <?php echo ($asset['purpose_function'] ?? '') == 'PPT Office' ? 'selected' : ''; ?>>PPT Office</option>
                            <option value="Control Post" <?php echo ($asset['purpose_function'] ?? '') == 'Control Post' ? 'selected' : ''; ?>>Control Post</option>
                            <option value="Barracks/Transit Camp" <?php echo ($asset['purpose_function'] ?? '') == 'Barracks/Transit Camp' ? 'selected' : ''; ?>>Barracks/Transit Camp</option>
                            <option value="FOB/MOB" <?php echo ($asset['purpose_function'] ?? '') == 'FOB/MOB' ? 'selected' : ''; ?>>FOB/MOB</option>
                            <option value="E-Border" <?php echo ($asset['purpose_function'] ?? '') == 'E-Border' ? 'selected' : ''; ?>>E-Border</option>
                            <option value="Flag House" <?php echo ($asset['purpose_function'] ?? '') == 'Flag House' ? 'selected' : ''; ?>>Flag House</option>
                            <option value="Zonal Command" <?php echo ($asset['purpose_function'] ?? '') == 'Zonal Command' ? 'selected' : ''; ?>>Zonal Command</option>
                            <option value="Migrant Holding Centers" <?php echo ($asset['purpose_function'] ?? '') == 'Migrant Holding Centers' ? 'selected' : ''; ?>>Migrant Holding Centers</option>
                            <option value="Others">Others</option>
                        </select>
                        <?php if (isset($errors['purpose_function'])): ?>
                            <small class="error-text"><?php echo $errors['purpose_function']; ?></small>
                        <?php endif; ?>
                    </div>
                    
                    <div class="form-group" id="purposeOtherWrapper" style="display: none;">
                        <label>Specify Other Purpose/Function</label>
                        <input type="text" name="purpose_other" id="purpose_other" class="form-control" 
                               placeholder="Enter purpose/function" value="<?php echo Security::escape($asset['purpose_other'] ?? ''); ?>">
                    </div>
                    <div class="form-group">
                    <label class="required">Address / Location Description</label>
                    <textarea name="address" required rows="3" 
                              class="form-control <?php echo isset($errors['address']) ? 'error' : ''; ?>"><?php echo Security::escape($asset['address']); ?></textarea>
                    <?php if (isset($errors['address'])): ?>
                        <small class="error-text"><?php echo $errors['address']; ?></small>
                    <?php endif; ?>
                </div>
                </div>
                
            </div>
            
            <!-- Location Information -->
            <div class="form-section-inner">
                <div class="section-title">
                    <h3><i class="fas fa-map-marker-alt"></i> Location Information</h3>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="required">State</label>
                        <select name="state_id" id="state_id" required 
                                class="form-control <?php echo isset($errors['state_id']) ? 'error' : ''; ?>">
                            <option value="">Select State</option>
                            <?php foreach ($states as $state): ?>
                            <option value="<?php echo $state['id']; ?>" 
                                    <?php echo $asset['state_id'] == $state['id'] ? 'selected' : ''; ?>>
                                <?php echo Security::escape($state['state_name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                        <?php if (isset($errors['state_id'])): ?>
                            <small class="error-text"><?php echo $errors['state_id']; ?></small>
                        <?php endif; ?>
                    </div>
                    
                    <div class="form-group">
                        <label class="required">Local Government Area (LGA)</label>
                        <select name="lga_id" id="lga_id" required 
                                class="form-control <?php echo isset($errors['lga_id']) ? 'error' : ''; ?>">
                            <option value="">Select State First</option>
                        </select>
                        <?php if (isset($errors['lga_id'])): ?>
                            <small class="error-text"><?php echo $errors['lga_id']; ?></small>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="required">Zone</label>
                        <select name="zone_id" id="zone_id" required 
                                class="form-control <?php echo isset($errors['zone_id']) ? 'error' : ''; ?>">
                            <option value="">Select Zone</option>
                            <?php foreach ($zones as $zone): ?>
                            <option value="<?php echo $zone['id']; ?>" 
                                    <?php echo $asset['zone_id'] == $zone['id'] ? 'selected' : ''; ?>>
                                <?php echo Security::escape($zone['zone_name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                        <?php if (isset($errors['zone_id'])): ?>
                            <small class="error-text"><?php echo $errors['zone_id']; ?></small>
                        <?php endif; ?>
                    </div>
                    
                    <div class="form-group">
                        <label class="required">Command / Formation</label>
                        <select name="command_id" id="command_id" required 
                                class="form-control <?php echo isset($errors['command_id']) ? 'error' : ''; ?>">
                            <option value="">Select Zone First</option>
                        </select>
                        <?php if (isset($errors['command_id'])): ?>
                            <small class="error-text"><?php echo $errors['command_id']; ?></small>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <!-- Building Details -->
            <div class="form-section-inner">
                <div class="section-title">
                    <h3><i class="fas fa-building"></i> Building Details</h3>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label>Floor Count</label>
                        <input type="number" name="floor_count" value="<?php echo Security::escape($asset['floor_count'] ?? ''); ?>" 
                               min="1" class="form-control">
                    </div>
                    
                    <div class="form-group">
                        <label>Total Area (m²)</label>
                        <input type="number" step="0.01" name="total_area" value="<?php echo Security::escape($asset['total_area'] ?? ''); ?>" 
                               class="form-control">
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label>Link Land Asset</label>
                        <select name="land_id" id="land_id" class="form-control">
                            <option value="">None (Standalone Building)</option>
                            <?php foreach ($landAssets as $land): ?>
                            <option value="<?php echo $land['id']; ?>" 
                                    <?php echo $asset['land_id'] == $land['id'] ? 'selected' : ''; ?>>
                                <?php echo Security::escape($land['asset_code'] . ' - ' . $land['address']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
            </div>
            
            <!-- Construction Details -->
            <div class="form-section-inner">
                <div class="section-title">
                    <h3><i class="fas fa-hard-hat"></i> Construction Details</h3>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label>Contractor</label>
                        <input type="text" name="construction_contractor" 
                               value="<?php echo Security::escape($asset['construction_contractor'] ?? ''); ?>" 
                               class="form-control" maxlength="255">
                    </div>
                    
                    <div class="form-group">
                        <label>Contract Sum (₦)</label>
                        <input type="number" step="0.01" name="contract_sum" 
                               value="<?php echo Security::escape($asset['contract_sum'] ?? ''); ?>" 
                               class="form-control">
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label>Date Awarded</label>
                        <input type="date" name="date_awarded" value="<?php echo Security::escape($asset['date_awarded'] ?? ''); ?>" 
                               class="form-control" max="<?php echo date('Y-m-d'); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label>Completion Date</label>
                        <input type="date" name="completion_date" value="<?php echo Security::escape($asset['completion_date'] ?? ''); ?>" 
                               class="form-control" max="<?php echo date('Y-m-d'); ?>">
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label>Date Occupied</label>
                        <input type="date" name="date_occupied" value="<?php echo Security::escape($asset['date_occupied'] ?? ''); ?>" 
                               class="form-control" max="<?php echo date('Y-m-d'); ?>">
                    </div>
                </div>
            </div>
            
            <!-- Status & Maintenance -->
            <div class="form-section-inner">
                <div class="section-title">
                    <h3><i class="fas fa-clipboard-check"></i> Status & Maintenance</h3>
                </div>
                
               <div class="form-row">
    <div class="form-group">
        <label class="required">Condition Status</label>
        <select name="condition_status" id="condition_status" required 
                class="form-control <?php echo isset($errors['condition_status']) ? 'error' : ''; ?>">
            <option value="">Select Condition</option>
            <option value="Under Construction" <?php echo ($asset['condition_status'] ?? '') == 'Under Construction' ? 'selected' : ''; ?>>Under Construction</option>
            <option value="Abandoned" <?php echo ($asset['condition_status'] ?? '') == 'Abandoned' ? 'selected' : ''; ?>>Abandoned</option>
            <option value="Dilapidated" <?php echo ($asset['condition_status'] ?? '') == 'Dilapidated' ? 'selected' : ''; ?>>Dilapidated</option>
            <option value="In Use" <?php echo ($asset['condition_status'] ?? '') == 'In Use' ? 'selected' : ''; ?>>In Use</option>
            <option value="Under Maintenance" <?php echo ($asset['condition_status'] ?? '') == 'Under Maintenance' ? 'selected' : ''; ?>>Under Maintenance</option>
            <option value="Other" <?php echo ($asset['condition_status'] ?? '') == 'Other' ? 'selected' : ''; ?>>Other</option>
        </select>
        <?php if (isset($errors['condition_status'])): ?>
            <small class="error-text"><?php echo $errors['condition_status']; ?></small>
        <?php endif; ?>
    </div>
    
    <div class="form-group">
        <label>Last Maintenance Date</label>
        <input type="date" name="last_maintenance_date" 
               value="<?php echo Security::escape($asset['last_maintenance_date'] ?? ''); ?>" 
               class="form-control" max="<?php echo date('Y-m-d'); ?>">
    </div>
</div>
            
            <!-- Remarks -->
            <div class="form-section-inner">
                <div class="section-title">
                    <h3><i class="fas fa-sticky-note"></i> Remarks</h3>
                </div>
                
                <div class="form-group">
                    <textarea name="remarks" rows="3" class="form-control"><?php echo Security::escape($asset['remarks'] ?? ''); ?></textarea>
                </div>
            </div>
            
            <!-- Existing Documents Section - Professional Redesign -->
            <?php if (!empty($documents)): ?>
            <div class="form-section-inner">
                <div class="section-title">
                    <h3><i class="fas fa-file-alt"></i> Existing Documents</h3>
                </div>
                
                <div class="existing-documents-grid">
                    <?php foreach ($documents as $index => $doc): ?>
                    <div class="existing-document-card" id="existing_doc_<?php echo $doc['id']; ?>">
                        <input type="hidden" name="existing_docs[<?php echo $index; ?>][id]" value="<?php echo $doc['id']; ?>">
                        <div class="document-preview">
                            <?php
                            $fileExt = strtolower(pathinfo($doc['file_name'], PATHINFO_EXTENSION));
                            $iconClass = 'fa-file';
                            if (in_array($fileExt, ['pdf'])) $iconClass = 'fa-file-pdf';
                            elseif (in_array($fileExt, ['jpg', 'jpeg', 'png'])) $iconClass = 'fa-file-image';
                            elseif (in_array($fileExt, ['doc', 'docx'])) $iconClass = 'fa-file-word';
                            ?>
                            <i class="fas <?php echo $iconClass; ?>"></i>
                        </div>
                        <div class="document-details">
                            <div class="document-name"><?php echo Security::escape($doc['file_name']); ?></div>
                            <div class="document-meta">
                                <span class="document-size"><?php echo round($doc['file_size'] / 1024, 2); ?> KB</span>
                                <span class="document-type"><?php echo strtoupper($fileExt); ?></span>
                            </div>
                        </div>
                        <div class="document-actions">
                            <a href="<?php echo BASE_URL . '/' . $doc['file_path']; ?>" target="_blank" class="btn-icon" title="View">
                                <i class="fas fa-eye"></i>
                            </a>
                            <button type="button" class="btn-icon delete" onclick="removeDocument(<?php echo $doc['id']; ?>)" title="Remove">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
            
            <!-- New Document Upload Section - Professional Redesign -->
            <div class="form-section-inner">
                <div class="section-title">
                    <h3><i class="fas fa-file-upload"></i> Add New Documents</h3>
                    <span class="badge badge-info">Optional - Max 5MB per file</span>
                </div>
                
                <div class="document-upload-container">
                    <div class="document-types-grid" id="documentTypesContainer">
                        <!-- Document type rows will be added here dynamically -->
                    </div>
                    
                    <div class="document-actions">
                        <button type="button" class="btn btn-outline-primary" id="addDocumentBtn">
                            <i class="fas fa-plus-circle"></i> Add Another Document
                        </button>
                    </div>
                    
                    <div class="upload-info">
                        <div class="info-item">
                            <i class="fas fa-info-circle text-info"></i>
                            <span>Allowed file types: PDF, JPG, PNG, DOC, DOCX</span>
                        </div>
                        <div class="info-item">
                            <i class="fas fa-database text-warning"></i>
                            <span>Maximum file size: 5MB per file</span>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Form Actions -->
            <div class="form-actions">
            <button type="submit" class="btn btn-success submit-btn" onclick="showSavingMessage(this); return false;">
                    <i class="fas fa-save"></i> Update Building Asset
            </button>
                <a href="<?php echo BASE_URL; ?>/buildings/show/<?php echo $asset['id']; ?>" class="btn btn-outline">
                    <i class="fas fa-times"></i> Cancel
                </a>
            </div>
        </form>
    </div>
</div>

<style>
/* Professional Document Upload Styles */
.document-upload-container {
    background: #f8fafc;
    border-radius: 12px;
    padding: 20px;
    border: 1px solid #e2e8f0;
    margin-top: 15px;
}

.document-types-grid {
    display: flex;
    flex-direction: column;
    gap: 15px;
    margin-bottom: 20px;
}

.document-row {
    display: grid;
    grid-template-columns: 250px 1fr 40px;
    gap: 15px;
    align-items: center;
    background: white;
    padding: 15px;
    border-radius: 8px;
    border: 1px solid #e2e8f0;
    transition: all 0.3s ease;
    position: relative;
}

.document-row:hover {
    border-color: #27ae60;
    box-shadow: 0 2px 8px rgba(39, 174, 96, 0.1);
}

.document-type-select {
    width: 100%;
    padding: 10px 12px;
    border: 1px solid #e2e8f0;
    border-radius: 6px;
    font-size: 0.95rem;
    background: white;
    cursor: pointer;
    transition: all 0.3s ease;
}

.document-type-select:hover,
.document-type-select:focus {
    border-color: #27ae60;
    outline: none;
    box-shadow: 0 0 0 3px rgba(39, 174, 96, 0.1);
}

.file-input-wrapper {
    position: relative;
    width: 100%;
}

.file-input-custom {
    width: 100%;
    padding: 10px 12px;
    border: 1px dashed #e2e8f0;
    border-radius: 6px;
    background: #f8fafc;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 10px;
    color: #64748b;
}

.file-input-custom:hover {
    border-color: #27ae60;
    background: #f0f9f4;
    color: #27ae60;
}

.file-input-custom i {
    font-size: 1.2rem;
}

.file-input-custom span {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.file-input-element {
    position: absolute;
    left: 0;
    top: 0;
    opacity: 0;
    width: 100%;
    height: 100%;
    cursor: pointer;
}

.remove-document-btn {
    width: 40px;
    height: 40px;
    border-radius: 8px;
    border: 1px solid #fee2e2;
    background: #fef2f2;
    color: #ef4444;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s ease;
}

.remove-document-btn:hover {
    background: #ef4444;
    color: white;
    border-color: #ef4444;
}

.remove-document-btn:disabled {
    opacity: 0.5;
    cursor: not-allowed;
    background: #f1f5f9;
    color: #94a3b8;
    border-color: #e2e8f0;
}

.document-actions {
    display: flex;
    justify-content: center;
    margin: 15px 0;
}

.btn-outline-primary {
    background: white;
    border: 1px solid #27ae60;
    color: #27ae60;
    padding: 10px 20px;
    border-radius: 6px;
    font-size: 0.95rem;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.btn-outline-primary:hover {
    background: #27ae60;
    color: white;
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(39, 174, 96, 0.2);
}

.btn-outline-primary i {
    font-size: 1rem;
}

.upload-info {
    margin-top: 20px;
    padding: 15px;
    background: #f1f5f9;
    border-radius: 8px;
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
}

.info-item {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 0.9rem;
    color: #475569;
}

.info-item i {
    font-size: 1rem;
}

/* Existing Documents Grid */
.existing-documents-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 15px;
    margin-top: 15px;
}

.existing-document-card {
    background: white;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    padding: 15px;
    display: flex;
    align-items: center;
    gap: 15px;
    transition: all 0.3s ease;
}

.existing-document-card:hover {
    border-color: #27ae60;
    box-shadow: 0 4px 12px rgba(0,0,0,0.05);
}

.document-preview {
    width: 40px;
    height: 40px;
    border-radius: 6px;
    background: #f1f5f9;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #27ae60;
    font-size: 1.5rem;
}

.document-details {
    flex: 1;
    min-width: 0;
}

.document-name {
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 4px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.document-meta {
    display: flex;
    gap: 10px;
    font-size: 0.8rem;
}

.document-size {
    color: #64748b;
}

.document-type {
    background: #e2e8f0;
    padding: 2px 6px;
    border-radius: 4px;
    color: #475569;
}

/* Badge styles */
.badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 500;
}

.badge-info {
    background: #e0f2f1;
    color: #00695c;
}

/* Responsive */
@media (max-width: 768px) {
    .document-row {
        grid-template-columns: 1fr;
        gap: 10px;
    }
    
    .remove-document-btn {
        position: absolute;
        top: 10px;
        right: 10px;
    }
    
    .existing-documents-grid {
        grid-template-columns: 1fr;
    }
    
    .upload-info {
        flex-direction: column;
        gap: 10px;
    }
}

/* Loading Message Overlay - Matching create.php style */
.saving-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
    animation: fadeIn 0.3s ease;
}

.saving-message {
    background: white;
    padding: 30px;
    border-radius: 12px;
    text-align: center;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
}

.saving-message i {
    font-size: 3rem;
    color: #27ae60;
    margin-bottom: 15px;
}

.saving-message p {
    font-size: 1.1rem;
    color: #333;
    margin: 0;
}

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.fa-pulse {
    animation: spin 1s linear infinite;
}

/* Alert Styles */
.alert {
    padding: 15px 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 10px;
    animation: slideIn 0.3s ease;
}

.alert-success {
    background: #d4edda;
    border: 1px solid #c3e6cb;
    color: #155724;
}

.alert-danger {
    background: #f8d7da;
    border: 1px solid #f5c6cb;
    color: #721c24;
}

.alert-info {
    background: #d1ecf1;
    border: 1px solid #bee5eb;
    color: #0c5460;
}

.alert i {
    font-size: 1.2rem;
}

.btn-close {
    margin-left: auto;
    background: none;
    border: none;
    font-size: 1.2rem;
    cursor: pointer;
    color: inherit;
    opacity: 0.7;
}

.btn-close:hover {
    opacity: 1;
}

@keyframes slideIn {
    from {
        transform: translateY(-20px);
        opacity: 0;
    }
    to {
        transform: translateY(0);
        opacity: 1;
    }
}

/*.form-group select#land_id {*/
/*    max-width: 400px;*/
/*    width: 100%;*/
/*}*/

/* Or to control all select boxes in form rows */
.form-row .form-group select {
    max-width: 465px;
    width: 100%;
}

/* Limit width for specific form fields */
.form-group select#land_id,
.form-group input[name="date_occupied"] {
    max-width: 465px;
    width: 100%;
}

</style>

<script>
// Define base URL for API calls
const baseUrl = '<?php echo BASE_URL; ?>';
const documentTypes = <?php echo json_encode($documentTypes); ?>;

let documentCount = 0;

document.addEventListener('DOMContentLoaded', function() {
    // State to LGA dropdown
    const stateSelect = document.getElementById('state_id');
    const lgaSelect = document.getElementById('lga_id');
    
    if (stateSelect) {
        stateSelect.addEventListener('change', function() {
            const stateId = this.value;
            
            if (!stateId) {
                lgaSelect.innerHTML = '<option value="">Select State First</option>';
                return;
            }
            
            const apiUrl = baseUrl.replace(/\/$/, '') + '/api/get_lgas.php?state_id=' + stateId;
            
            fetch(apiUrl)
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        lgaSelect.innerHTML = '<option value="">Error loading LGAs</option>';
                        return;
                    }
                    
                    lgaSelect.innerHTML = '<option value="">Select LGA</option>';
                    if (data && data.length > 0) {
                        data.forEach(lga => {
                            const option = document.createElement('option');
                            option.value = lga.id;
                            option.textContent = lga.lga_name;
                            lgaSelect.appendChild(option);
                        });
                        
                        <?php if (!empty($asset['lga_id'])): ?>
                        lgaSelect.value = '<?php echo $asset['lga_id']; ?>';
                        <?php endif; ?>
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    lgaSelect.innerHTML = '<option value="">Error loading LGAs</option>';
                });
        });
        
        <?php if (!empty($asset['state_id'])): ?>
        stateSelect.value = '<?php echo $asset['state_id']; ?>';
        stateSelect.dispatchEvent(new Event('change'));
        <?php endif; ?>
    }
    
    // Zone to Command dropdown
    const zoneSelect = document.getElementById('zone_id');
    const commandSelect = document.getElementById('command_id');
    
    if (zoneSelect) {
        zoneSelect.addEventListener('change', function() {
            const zoneId = this.value;
            
            if (!zoneId) {
                commandSelect.innerHTML = '<option value="">Select Zone First</option>';
                return;
            }
            
            const apiUrl = baseUrl.replace(/\/$/, '') + '/api/get_commands.php?zone_id=' + zoneId;
            
            fetch(apiUrl)
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        commandSelect.innerHTML = '<option value="">Error loading commands</option>';
                        return;
                    }
                    
                    commandSelect.innerHTML = '<option value="">Select Command</option>';
                    if (data && data.length > 0) {
                        data.forEach(cmd => {
                            const option = document.createElement('option');
                            option.value = cmd.id;
                            option.textContent = cmd.command_name;
                            commandSelect.appendChild(option);
                        });
                        
                        <?php if (!empty($asset['command_id'])): ?>
                        commandSelect.value = '<?php echo $asset['command_id']; ?>';
                        <?php endif; ?>
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    commandSelect.innerHTML = '<option value="">Error loading commands</option>';
                });
        });
        
        <?php if (!empty($asset['zone_id'])): ?>
        zoneSelect.value = '<?php echo $asset['zone_id']; ?>';
        zoneSelect.dispatchEvent(new Event('change'));
        <?php endif; ?>
    }
    
    // Purpose/Function other field
    const purposeSelect = document.getElementById('purpose_function');
    const purposeWrapper = document.getElementById('purposeOtherWrapper');
    const purposeOther = document.getElementById('purpose_other');
    
    if (purposeSelect) {
        purposeSelect.addEventListener('change', function() {
            if (this.value === 'Others') {
                purposeWrapper.style.display = 'block';
                if (purposeOther) purposeOther.required = true;
            } else {
                purposeWrapper.style.display = 'none';
                if (purposeOther) {
                    purposeOther.required = false;
                    purposeOther.value = '';
                }
            }
        });
        
        <?php if (($asset['purpose_function'] ?? '') === 'Others'): ?>
        purposeWrapper.style.display = 'block';
        <?php endif; ?>
    }
    
    // Building type other field
    const typeSelect = document.getElementById('building_type');
    const typeOtherWrapper = document.getElementById('typeOtherWrapper');
    const typeOther = document.getElementById('building_type_other');
    
    if (typeSelect && !typeOtherWrapper) {
        // Create other wrapper if it doesn't exist
        const wrapper = document.createElement('div');
        wrapper.id = 'typeOtherWrapper';
        wrapper.className = 'form-group';
        wrapper.style.display = 'none';
        wrapper.innerHTML = `
            <label>Specify Building Type</label>
            <input type="text" name="building_type_other" id="building_type_other" class="form-control" placeholder="Enter building type">
        `;
        typeSelect.parentNode.appendChild(wrapper);
        
        typeSelect.addEventListener('change', function() {
            const wrapper = document.getElementById('typeOtherWrapper');
            const otherInput = document.getElementById('building_type_other');
            if (this.value === 'Other') {
                wrapper.style.display = 'block';
                otherInput.required = true;
            } else {
                wrapper.style.display = 'none';
                otherInput.required = false;
                otherInput.value = '';
            }
        });
        
        <?php if (!in_array($asset['building_type'] ?? '', ['Office', 'Residential', 'Warehouse', 'Barracks', 'Training Facility', 'Medical Center'])): ?>
        typeSelect.value = 'Other';
        typeSelect.dispatchEvent(new Event('change'));
        if (typeOther) typeOther.value = '<?php echo Security::escape($asset['building_type']); ?>';
        <?php endif; ?>
    }
    
    // Initialize document upload
    addDocumentRow();
    
    // Add Document button click handler
    document.getElementById('addDocumentBtn').addEventListener('click', function() {
        addDocumentRow();
    });
});

function addDocumentRow() {
    const container = document.getElementById('documentTypesContainer');
    if (!container) return;
    
    const rowId = 'doc_row_' + documentCount;
    
    const row = document.createElement('div');
    row.className = 'document-row';
    row.id = rowId;
    
    // Create dropdown options
    let options = '<option value="">Select Document Type</option>';
    for (const [value, label] of Object.entries(documentTypes)) {
        options += `<option value="${value}">${label}</option>`;
    }
    
    row.innerHTML = `
        <select name="document_types[]" class="document-type-select">
            ${options}
        </select>
        <div class="file-input-wrapper">
            <div class="file-input-custom" id="custom_${rowId}">
                <i class="fas fa-cloud-upload-alt"></i>
                <span>Choose file...</span>
            </div>
            <input type="file" name="new_documents[]" class="file-input-element" 
                   accept=".pdf,.jpg,.jpeg,.png,.doc,.docx" 
                   data-custom="custom_${rowId}"
                   onchange="updateFileLabel(this, '${rowId}')">
        </div>
        <button type="button" class="remove-document-btn" onclick="removeDocumentRow('${rowId}')" ${documentCount === 0 ? 'disabled' : ''}>
            <i class="fas fa-times"></i>
        </button>
    `;
    
    container.appendChild(row);
    documentCount++;
}

function updateFileLabel(input, rowId) {
    const customDiv = document.getElementById('custom_' + rowId);
    if (customDiv) {
        if (input.files && input.files[0]) {
            const file = input.files[0];
            const fileSizeMB = (file.size / 1024 / 1024).toFixed(2);
            
            // Check file size (5MB max)
            if (file.size > 5 * 1024 * 1024) {
                alert('File ' + file.name + ' exceeds 5MB limit. Please choose a smaller file.');
                input.value = '';
                customDiv.innerHTML = '<i class="fas fa-cloud-upload-alt"></i><span>Choose file...</span>';
                customDiv.style.borderColor = '#e2e8f0';
                customDiv.style.background = '#f8fafc';
                return;
            }
            
            // Check file type
            const allowedTypes = ['pdf', 'jpg', 'jpeg', 'png', 'doc', 'docx'];
            const fileExt = file.name.split('.').pop().toLowerCase();
            
            if (!allowedTypes.includes(fileExt)) {
                alert('File type not allowed. Allowed types: PDF, JPG, PNG, DOC, DOCX');
                input.value = '';
                customDiv.innerHTML = '<i class="fas fa-cloud-upload-alt"></i><span>Choose file...</span>';
                customDiv.style.borderColor = '#e2e8f0';
                customDiv.style.background = '#f8fafc';
                return;
            }
            
            customDiv.innerHTML = `<i class="fas fa-check-circle text-success"></i><span>${file.name} (${fileSizeMB} MB)</span>`;
            customDiv.style.borderColor = '#27ae60';
            customDiv.style.background = '#f0f9f4';
        } else {
            customDiv.innerHTML = '<i class="fas fa-cloud-upload-alt"></i><span>Choose file...</span>';
            customDiv.style.borderColor = '#e2e8f0';
            customDiv.style.background = '#f8fafc';
        }
    }
}

function removeDocumentRow(rowId) {
    const row = document.getElementById(rowId);
    if (row && documentCount > 1) {
        row.remove();
        documentCount--;
    } else if (documentCount === 1) {
        alert('At least one document row must remain. You can leave it empty if you don\'t want to upload any documents.');
    }
}

function removeDocument(docId) {
    if (confirm('Are you sure you want to remove this document? This action cannot be undone.')) {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'remove_docs[]';
        input.value = docId;
        document.getElementById('buildingForm').appendChild(input);
        
        const docElement = document.getElementById('existing_doc_' + docId);
        if (docElement) {
            docElement.remove();
        }
        
        if (typeof showNotification === 'function') {
            showNotification('success', 'Document will be removed upon update');
        }
    }
}

// Add form submission handling with loading message - EXACTLY like create.php
function showSavingMessage(button) {
    // Create saving overlay
    const overlay = document.createElement('div');
    overlay.className = 'saving-overlay';
    overlay.id = 'savingOverlay';
    overlay.innerHTML = `
        <div class="saving-message">
            <i class="fas fa-spinner fa-pulse"></i>
            <p>Updating building asset... Please wait</p>
        </div>
    `;
    document.body.appendChild(overlay);
    
    // Disable the submit button to prevent double submission
    button.disabled = true;
    
    // Submit the form
    document.getElementById('buildingForm').submit();
}

// Auto-hide success/error messages after 5 seconds
document.addEventListener('DOMContentLoaded', function() {
    const successAlert = document.getElementById('successAlert');
    if (successAlert) {
        setTimeout(function() {
            successAlert.style.display = 'none';
        }, 5000);
    }
    
    const errorAlert = document.getElementById('errorAlert');
    if (errorAlert) {
        setTimeout(function() {
            errorAlert.style.display = 'none';
        }, 5000);
    }
});
</script>

