<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<main class="main-content" id="mainContent">
    <header class="main-header">
        <div>
            <h1>AGENCIES MANAGEMENT</h1>
            <p class="welcome-text">Manage modeling agencies and their information</p>
        </div>
        <div class="header-actions">
            <button class="btn btn-primary" onclick="openCreateModal()">
                <i class="fas fa-plus"></i> Add Agency
            </button>
        </div>
    </header>

    <!-- Agencies Stats -->
    <div class="metrics-cards">
        <div class="card stat-card">
            <div class="card-icon">
                <i class="fas fa-building"></i>
            </div>
            <div class="card-content">
                <p class="card-label">TOTAL AGENCIES</p>
                <div class="card-data">
                    <span class="value" id="totalAgencies"><?php echo count($agencies); ?></span>
                    <span class="change positive">+0%</span>
                </div>
            </div>
        </div>

        <div class="card stat-card">
            <div class="card-icon">
                <i class="fas fa-check-circle"></i>
            </div>
            <div class="card-content">
                <p class="card-label">ACTIVE AGENCIES</p>
                <div class="card-data">
                    <span class="value" id="activeAgencies">
                        <?php 
                            $active_count = 0;
                            foreach ($agencies as $agency) {
                                if ($agency->status === 'active') $active_count++;
                            }
                            echo $active_count;
                        ?>
                    </span>
                    <span class="change positive">+0%</span>
                </div>
            </div>
        </div>

        <div class="card stat-card">
            <div class="card-icon">
                <i class="fas fa-users"></i>
            </div>
            <div class="card-content">
                <p class="card-label">AGENCY PROJECTS</p>
                <div class="card-data">
                    <span class="value" id="agencyProjects">0</span>
                    <span class="change positive">+0%</span>
                </div>
            </div>
        </div>

        <div class="card stat-card">
            <div class="card-icon">
                <i class="fas fa-chart-line"></i>
            </div>
            <div class="card-content">
                <p class="card-label">GROWTH RATE</p>
                <div class="card-data">
                    <span class="value" id="growthRate">12%</span>
                    <span class="change positive">+2%</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Agencies List -->
    <div class="content-area">
        <div class="section-header">
            <h2>Agencies List</h2>
            <div class="search-container">
                <input type="text" id="agencySearch" placeholder="Search agencies..." class="search-input" onkeyup="searchAgencies()">
                <i class="fas fa-search search-icon"></i>
            </div>
        </div>

        <div class="agencies-grid" id="agenciesList">
            <?php if (!empty($agencies)): ?>
                <?php foreach ($agencies as $agency): ?>
                <div class="agency-card" data-id="<?php echo $agency->id; ?>">
                    <div class="agency-header">
                        <div class="agency-logo-container">
                            <?php if ($agency->logo && file_exists($agency->logo)): ?>
                                <img src="<?php echo base_url($agency->logo); ?>" alt="<?php echo htmlspecialchars($agency->name); ?>" class="agency-logo">
                            <?php else: ?>
                                <div class="agency-logo-placeholder">
                                    <i class="fas fa-building"></i>
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="agency-info">
                            <h3 class="agency-name"><?php echo htmlspecialchars($agency->name); ?></h3>
                            <span class="agency-status <?php echo $agency->status; ?>">
                                <?php echo ucfirst($agency->status); ?>
                            </span>
                        </div>
                        <div class="agency-actions">
                            <button class="btn-icon" onclick="editAgency(<?php echo $agency->id; ?>)" title="Edit Agency">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn-icon btn-danger" onclick="deleteAgency(<?php echo $agency->id; ?>)" title="Delete Agency">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                    
                    <div class="agency-details">
                        <?php if ($agency->contact_email): ?>
                        <div class="agency-detail">
                            <i class="fas fa-envelope"></i>
                            <span><?php echo htmlspecialchars($agency->contact_email); ?></span>
                        </div>
                        <?php endif; ?>
                        
                        <?php if ($agency->contact_phone): ?>
                        <div class="agency-detail">
                            <i class="fas fa-phone"></i>
                            <span><?php echo htmlspecialchars($agency->contact_phone); ?></span>
                        </div>
                        <?php endif; ?>
                        
                        <?php if ($agency->address): ?>
                        <div class="agency-detail">
                            <i class="fas fa-map-marker-alt"></i>
                            <span><?php echo htmlspecialchars($agency->address); ?></span>
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <div class="agency-footer">
                        <small>Created: <?php echo date('M j, Y', strtotime($agency->created_at)); ?></small>
                        <small>Updated: <?php echo date('M j, Y', strtotime($agency->updated_at)); ?></small>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="empty-state">
                    <div class="empty-icon">
                        <i class="fas fa-building"></i>
                    </div>
                    <h3>No Agencies Found</h3>
                    <p>Get started by adding your first modeling agency</p>
                    <button class="btn btn-primary" onclick="openCreateModal()">
                        <i class="fas fa-plus"></i> Add Your First Agency
                    </button>
                </div>
            <?php endif; ?>
        </div>
    </div>
</main>

<!-- Create/Edit Agency Modal -->
<div id="agencyModal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modalTitle">Add New Agency</h3>
            <button class="btn-close" onclick="closeModal()">&times;</button>
        </div>
        <form id="agencyForm" enctype="multipart/form-data">
            <div class="modal-body">
                <div class="form-group">
                    <label class="form-label">Agency Name *</label>
                    <input type="text" name="name" class="form-input" required>
                    <div class="error-message" id="nameError"></div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Logo *</label>
                    <div class="file-upload-container">
                        <input type="file" name="logo" id="logoInput" class="file-input" accept="image/*" required>
                        <label for="logoInput" class="file-upload-label">
                            <i class="fas fa-upload"></i>
                            <span>Choose Logo</span>
                        </label>
                        <div class="file-preview" id="logoPreview"></div>
                    </div>
                    <div class="error-message" id="logoError"></div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Contact Email</label>
                    <input type="email" name="contact_email" class="form-input">
                    <div class="error-message" id="emailError"></div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Contact Phone</label>
                    <input type="text" name="contact_phone" class="form-input">
                    <div class="error-message" id="phoneError"></div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Address</label>
                    <textarea name="address" class="form-textarea" rows="3"></textarea>
                    <div class="error-message" id="addressError"></div>
                </div>
                
                <div class="form-group" id="statusField" style="display: none;">
                    <label class="form-label">Status</label>
                    <select name="status" class="form-select">
                        <option value="active">Active</option>
                        <option value="inactive">Inactive</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeModal()">Cancel</button>
                <button type="submit" class="btn btn-primary" id="submitBtn">Create Agency</button>
            </div>
        </form>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div id="deleteAgencyModal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3>Delete Agency</h3>
            <button class="btn-close" onclick="closeDeleteModal()">&times;</button>
        </div>
        <div class="modal-body">
            <p>Are you sure you want to delete agency "<span id="agencyNameToDelete"></span>"?</p>
            <p class="warning-text">This action cannot be undone. All agency information will be permanently deleted.</p>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeDeleteModal()">Cancel</button>
            <button class="btn btn-danger" id="confirmDeleteBtn">Delete Agency</button>
        </div>
    </div>
</div>

<style>
.agencies-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: 20px;
}

.agency-card {
    background: var(--card-bg);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    padding: 20px;
    transition: all 0.3s ease;
}

.agency-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 30px rgba(0,0,0,0.12);
}

.agency-header {
    display: flex;
    align-items: flex-start;
    gap: 15px;
    margin-bottom: 15px;
}

.agency-logo-container {
    flex-shrink: 0;
}

.agency-logo {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    object-fit: cover;
    border: 2px solid var(--border-color);
}

.agency-logo-placeholder {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    background: linear-gradient(135deg, #667eea, #764ba2);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 24px;
}

.agency-info {
    flex: 1;
}

.agency-name {
    margin: 0 0 8px 0;
    font-size: 18px;
    font-weight: 700;
    color: var(--text-color);
}

.agency-status {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    text-transform: uppercase;
}

.agency-status.active {
    background: #e8f5e8;
    color: #2e7d32;
}

.agency-status.inactive {
    background: #ffebee;
    color: #c62828;
}

.agency-actions {
    display: flex;
    gap: 8px;
}

.agency-details {
    display: flex;
    flex-direction: column;
    gap: 8px;
    margin-bottom: 15px;
}

.agency-detail {
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 14px;
    color: var(--light-text);
}

.agency-detail i {
    width: 16px;
    text-align: center;
    color: var(--text-color);
}

.agency-footer {
    display: flex;
    justify-content: space-between;
    padding-top: 15px;
    border-top: 1px solid var(--border-color);
    font-size: 12px;
    color: var(--light-text);
}

.file-upload-container {
    margin-bottom: 10px;
}

.file-input {
    display: none;
}

.file-upload-label {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 12px 20px;
    background: var(--border-color);
    border: 2px dashed #ccc;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
    text-align: center;
}

.file-upload-label:hover {
    border-color: var(--primary-color);
    background: #f0f0f0;
}

.file-preview {
    margin-top: 10px;
    text-align: center;
}

.file-preview img {
    max-width: 200px;
    max-height: 200px;
    border-radius: 8px;
    border: 2px solid var(--border-color);
}

.error-message {
    color: #dc3545;
    font-size: 12px;
    margin-top: 5px;
    display: none;
}
</style>

<script>
let currentAgencyId = null;
let agencyToDelete = null;

function openCreateModal() {
    currentAgencyId = null;
    document.getElementById('modalTitle').textContent = 'Add New Agency';
    document.getElementById('submitBtn').textContent = 'Create Agency';
    document.getElementById('statusField').style.display = 'none';
    document.getElementById('agencyForm').reset();
    document.getElementById('logoPreview').innerHTML = '';
    document.getElementById('logoInput').required = true;
    
    clearErrors();
    document.getElementById('agencyModal').style.display = 'flex';
}

async function editAgency(agencyId) {
    try {
        const response = await fetch(`<?php echo base_url('admin/get_agency_details/'); ?>${agencyId}`);
        const data = await response.json();
        
        if (data.success) {
            currentAgencyId = agencyId;
            const agency = data.agency;
            
            document.getElementById('modalTitle').textContent = 'Edit Agency';
            document.getElementById('submitBtn').textContent = 'Update Agency';
            document.getElementById('statusField').style.display = 'block';
            
            document.querySelector('input[name="name"]').value = agency.name || '';
            document.querySelector('input[name="contact_email"]').value = agency.contact_email || '';
            document.querySelector('input[name="contact_phone"]').value = agency.contact_phone || '';
            document.querySelector('textarea[name="address"]').value = agency.address || '';
            document.querySelector('select[name="status"]').value = agency.status || 'active';
            
            // Show logo preview if exists
            if (agency.logo) {
                document.getElementById('logoPreview').innerHTML = `
                    <img src="<?php echo base_url(); ?>${agency.logo}" alt="Current Logo">
                    <p style="margin-top: 8px; font-size: 12px; color: var(--light-text);">Current logo</p>
                `;
            }
            
            document.getElementById('logoInput').required = false;
            clearErrors();
            document.getElementById('agencyModal').style.display = 'flex';
        }
    } catch (error) {
        console.error('Error loading agency details:', error);
        alert('Failed to load agency details');
    }
}

function deleteAgency(agencyId) {
    const agencyCard = document.querySelector(`.agency-card[data-id="${agencyId}"]`);
    const agencyName = agencyCard.querySelector('.agency-name').textContent;
    
    agencyToDelete = agencyId;
    document.getElementById('agencyNameToDelete').textContent = agencyName;
    document.getElementById('deleteAgencyModal').style.display = 'flex';
}

async function confirmDeleteAgency() {
    if (!agencyToDelete) return;
    
    try {
        const response = await fetch(`<?php echo base_url('admin/delete_agency/'); ?>${agencyToDelete}`, {
            method: 'DELETE'
        });
        
        const data = await response.json();
        
        if (data.success) {
            showNotification('Agency deleted successfully!', 'success');
            closeDeleteModal();
            // Remove agency card from UI
            document.querySelector(`.agency-card[data-id="${agencyToDelete}"]`).remove();
            updateAgencyStats();
        } else {
            showNotification(data.message || 'Failed to delete agency', 'error');
        }
    } catch (error) {
        console.error('Error deleting agency:', error);
        showNotification('Error deleting agency', 'error');
    }
}

document.getElementById('agencyForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const url = currentAgencyId 
        ? `<?php echo base_url('admin/update_agency/'); ?>${currentAgencyId}`
        : `<?php echo base_url('admin/create_agency'); ?>`;
    
    try {
        const response = await fetch(url, {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.success) {
            showNotification(data.message, 'success');
            closeModal();
            location.reload(); // Reload to show updated list
        } else {
            showErrors(data.errors);
        }
    } catch (error) {
        console.error('Error saving agency:', error);
        showNotification('Error saving agency', 'error');
    }
});

// Logo preview
document.getElementById('logoInput').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('logoPreview').innerHTML = `
                <img src="${e.target.result}" alt="Logo Preview">
            `;
        };
        reader.readAsDataURL(file);
    }
});

function closeModal() {
    document.getElementById('agencyModal').style.display = 'none';
}

function closeDeleteModal() {
    agencyToDelete = null;
    document.getElementById('deleteAgencyModal').style.display = 'none';
}

function showErrors(errors) {
    clearErrors();
    for (const field in errors) {
        const errorElement = document.getElementById(field + 'Error');
        if (errorElement) {
            errorElement.textContent = errors[field];
            errorElement.style.display = 'block';
        }
    }
}

function clearErrors() {
    const errorElements = document.querySelectorAll('.error-message');
    errorElements.forEach(element => {
        element.textContent = '';
        element.style.display = 'none';
    });
}

function searchAgencies() {
    const searchTerm = document.getElementById('agencySearch').value.toLowerCase();
    const agencyCards = document.querySelectorAll('.agency-card');
    
    agencyCards.forEach(card => {
        const agencyName = card.querySelector('.agency-name').textContent.toLowerCase();
        if (agencyName.includes(searchTerm)) {
            card.style.display = 'block';
        } else {
            card.style.display = 'none';
        }
    });
}

function updateAgencyStats() {
    const totalAgencies = document.querySelectorAll('.agency-card').length;
    const activeAgencies = document.querySelectorAll('.agency-status.active').length;
    
    document.getElementById('totalAgencies').textContent = totalAgencies;
    document.getElementById('activeAgencies').textContent = activeAgencies;
}

function showNotification(message, type) {
    // Use your existing notification function
    alert(message); // Replace with your notification system
}

// Event listeners
document.getElementById('confirmDeleteBtn').addEventListener('click', confirmDeleteAgency);

// Close modals on outside click
document.getElementById('agencyModal').addEventListener('click', function(e) {
    if (e.target === this) closeModal();
});

document.getElementById('deleteAgencyModal').addEventListener('click', function(e) {
    if (e.target === this) closeDeleteModal();
});
</script>