<?php
/**
 * ============================================================================
 * admin/locations.php - Location Hierarchy Management
 * ============================================================================
 */

// Include admin base (handles authentication & permissions)
require_once __DIR__ . '/includes/base.php';

// Get active tab
$activeTab = $_GET['tab'] ?? 'regions';

// Define breadcrumbs
$breadcrumbs = [
    ['title' => 'Locations', 'url' => '']
];

// Fetch data based on active tab
switch ($activeTab) {
    case 'regions':
        $sql = "SELECT * FROM regions ORDER BY region_name";
        $stmt = $db->query($sql);
        $items = $stmt->fetchAll();
        break;
        
    case 'districts':
        $sql = "SELECT d.*, r.region_name 
                FROM districts d 
                JOIN regions r ON d.region_id = r.id 
                ORDER BY r.region_name, d.district_name";
        $stmt = $db->query($sql);
        $items = $stmt->fetchAll();
        break;
        
    case 'subcounties':
        $sql = "SELECT s.*, d.district_name, r.region_name 
                FROM subcounties s 
                JOIN districts d ON s.district_id = d.id 
                JOIN regions r ON d.region_id = r.id 
                ORDER BY r.region_name, d.district_name, s.subcounty_name";
        $stmt = $db->query($sql);
        $items = $stmt->fetchAll();
        break;
        
    case 'parishes':
        $sql = "SELECT p.*, s.subcounty_name, d.district_name 
                FROM parishes p 
                JOIN subcounties s ON p.subcounty_id = s.id 
                JOIN districts d ON s.district_id = d.id 
                ORDER BY d.district_name, s.subcounty_name, p.parish_name";
        $stmt = $db->query($sql);
        $items = $stmt->fetchAll();
        break;
        
    case 'villages':
        $sql = "SELECT v.*, p.parish_name, s.subcounty_name, d.district_name 
                FROM villages v 
                JOIN parishes p ON v.parish_id = p.id 
                JOIN subcounties s ON p.subcounty_id = s.id 
                JOIN districts d ON s.district_id = d.id 
                ORDER BY d.district_name, s.subcounty_name, p.parish_name, v.village_name";
        $stmt = $db->query($sql);
        $items = $stmt->fetchAll();
        break;
}

// Get counts
$counts = [];
$counts['regions'] = $db->query("SELECT COUNT(*) FROM regions")->fetchColumn();
$counts['districts'] = $db->query("SELECT COUNT(*) FROM districts")->fetchColumn();
$counts['subcounties'] = $db->query("SELECT COUNT(*) FROM subcounties")->fetchColumn();
$counts['parishes'] = $db->query("SELECT COUNT(*) FROM parishes")->fetchColumn();
$counts['villages'] = $db->query("SELECT COUNT(*) FROM villages")->fetchColumn();

// Start rendering
renderAdminHeader('Location Management', $breadcrumbs);
?>

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1 fw-bold">Location Management</h2>
        <p class="text-muted mb-0">Manage regions, districts, subcounties, parishes, and villages</p>
    </div>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addLocationModal">
        <i class="bi bi-plus-circle me-2"></i>Add <?php echo ucfirst(rtrim($activeTab, 's')); ?>
    </button>
</div>

<!-- Statistics Cards -->
<div class="row mb-4">
    <div class="col-lg mb-3">
        <div class="card stat-card border-0 shadow-sm h-100">
            <div class="card-body text-center">
                <div class="text-primary mb-2" style="font-size: 2rem;"><i class="bi bi-globe"></i></div>
                <h3 class="mb-0 fw-bold"><?php echo $counts['regions']; ?></h3>
                <small class="text-muted">Regions</small>
            </div>
        </div>
    </div>
    <div class="col-lg mb-3">
        <div class="card stat-card border-0 shadow-sm h-100">
            <div class="card-body text-center">
                <div class="text-success mb-2" style="font-size: 2rem;"><i class="bi bi-map"></i></div>
                <h3 class="mb-0 fw-bold"><?php echo $counts['districts']; ?></h3>
                <small class="text-muted">Districts</small>
            </div>
        </div>
    </div>
    <div class="col-lg mb-3">
        <div class="card stat-card border-0 shadow-sm h-100">
            <div class="card-body text-center">
                <div class="text-info mb-2" style="font-size: 2rem;"><i class="bi bi-signpost"></i></div>
                <h3 class="mb-0 fw-bold"><?php echo $counts['subcounties']; ?></h3>
                <small class="text-muted">Subcounties</small>
            </div>
        </div>
    </div>
    <div class="col-lg mb-3">
        <div class="card stat-card border-0 shadow-sm h-100">
            <div class="card-body text-center">
                <div class="text-warning mb-2" style="font-size: 2rem;"><i class="bi bi-signpost-2"></i></div>
                <h3 class="mb-0 fw-bold"><?php echo $counts['parishes']; ?></h3>
                <small class="text-muted">Parishes</small>
            </div>
        </div>
    </div>
    <div class="col-lg mb-3">
        <div class="card stat-card border-0 shadow-sm h-100">
            <div class="card-body text-center">
                <div class="text-danger mb-2" style="font-size: 2rem;"><i class="bi bi-house"></i></div>
                <h3 class="mb-0 fw-bold"><?php echo $counts['villages']; ?></h3>
                <small class="text-muted">Villages</small>
            </div>
        </div>
    </div>
</div>

<!-- Navigation Tabs -->
<ul class="nav nav-tabs mb-4">
    <li class="nav-item">
        <a class="nav-link <?php echo $activeTab === 'regions' ? 'active' : ''; ?>" href="?tab=regions">
            <i class="bi bi-globe me-2"></i>Regions
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link <?php echo $activeTab === 'districts' ? 'active' : ''; ?>" href="?tab=districts">
            <i class="bi bi-map me-2"></i>Districts
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link <?php echo $activeTab === 'subcounties' ? 'active' : ''; ?>" href="?tab=subcounties">
            <i class="bi bi-signpost me-2"></i>Subcounties
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link <?php echo $activeTab === 'parishes' ? 'active' : ''; ?>" href="?tab=parishes">
            <i class="bi bi-signpost-2 me-2"></i>Parishes
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link <?php echo $activeTab === 'villages' ? 'active' : ''; ?>" href="?tab=villages">
            <i class="bi bi-house me-2"></i>Villages
        </a>
    </li>
</ul>

<!-- Data Table -->
<div class="card border-0 shadow-sm">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0" id="locationsTable">
                <thead class="table-light">
                    <tr>
                        <?php if ($activeTab === 'regions'): ?>
                            <th>ID</th>
                            <th>Region Name</th>
                            <th>Region Code</th>
                            <th>Created</th>
                            <th class="text-end">Actions</th>
                        <?php elseif ($activeTab === 'districts'): ?>
                            <th>ID</th>
                            <th>District Name</th>
                            <th>Region</th>
                            <th>District Code</th>
                            <th>Created</th>
                            <th class="text-end">Actions</th>
                        <?php elseif ($activeTab === 'subcounties'): ?>
                            <th>ID</th>
                            <th>Subcounty Name</th>
                            <th>District</th>
                            <th>Region</th>
                            <th>Code</th>
                            <th class="text-end">Actions</th>
                        <?php elseif ($activeTab === 'parishes'): ?>
                            <th>ID</th>
                            <th>Parish Name</th>
                            <th>Subcounty</th>
                            <th>District</th>
                            <th>Code</th>
                            <th class="text-end">Actions</th>
                        <?php else: ?>
                            <th>ID</th>
                            <th>Village Name</th>
                            <th>Parish</th>
                            <th>Subcounty</th>
                            <th>District</th>
                            <th class="text-end">Actions</th>
                        <?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($items as $item): ?>
                    <tr>
                        <td><small class="text-muted">#<?php echo $item['id']; ?></small></td>
                        <td class="fw-semibold">
                            <?php 
                            if ($activeTab === 'regions') echo htmlspecialchars($item['region_name']);
                            elseif ($activeTab === 'districts') echo htmlspecialchars($item['district_name']);
                            elseif ($activeTab === 'subcounties') echo htmlspecialchars($item['subcounty_name']);
                            elseif ($activeTab === 'parishes') echo htmlspecialchars($item['parish_name']);
                            else echo htmlspecialchars($item['village_name']);
                            ?>
                        </td>
                        <?php if ($activeTab === 'regions'): ?>
                            <td><span class="badge bg-primary"><?php echo htmlspecialchars($item['region_code']); ?></span></td>
                            <td><small class="text-muted"><?php echo formatDate($item['created_at']); ?></small></td>
                        <?php elseif ($activeTab === 'districts'): ?>
                            <td><?php echo htmlspecialchars($item['region_name']); ?></td>
                            <td><span class="badge bg-success"><?php echo htmlspecialchars($item['district_code']); ?></span></td>
                            <td><small class="text-muted"><?php echo formatDate($item['created_at']); ?></small></td>
                        <?php elseif ($activeTab === 'subcounties'): ?>
                            <td><?php echo htmlspecialchars($item['district_name']); ?></td>
                            <td><small class="text-muted"><?php echo htmlspecialchars($item['region_name']); ?></small></td>
                            <td><span class="badge bg-info"><?php echo htmlspecialchars($item['subcounty_code']); ?></span></td>
                        <?php elseif ($activeTab === 'parishes'): ?>
                            <td><?php echo htmlspecialchars($item['subcounty_name']); ?></td>
                            <td><small class="text-muted"><?php echo htmlspecialchars($item['district_name']); ?></small></td>
                            <td><span class="badge bg-warning"><?php echo htmlspecialchars($item['parish_code'] ?? 'N/A'); ?></span></td>
                        <?php else: ?>
                            <td><?php echo htmlspecialchars($item['parish_name']); ?></td>
                            <td><?php echo htmlspecialchars($item['subcounty_name']); ?></td>
                            <td><small class="text-muted"><?php echo htmlspecialchars($item['district_name']); ?></small></td>
                        <?php endif; ?>
                        <td class="text-end">
                            <div class="btn-group btn-group-sm">
                                <button class="btn btn-outline-primary" onclick="editLocation(<?php echo $item['id']; ?>, '<?php echo $activeTab; ?>')" title="Edit">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <button class="btn btn-outline-danger" onclick="deleteLocation(<?php echo $item['id']; ?>, '<?php echo $activeTab; ?>')" title="Delete">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add Location Modal -->
<div class="modal fade" id="addLocationModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-plus-circle me-2"></i>Add <?php echo ucfirst(rtrim($activeTab, 's')); ?>
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="addLocationForm">
                <div class="modal-body">
                    <input type="hidden" name="type" value="<?php echo $activeTab; ?>">
                    
                    <?php if ($activeTab !== 'regions'): ?>
                    <div class="mb-3">
                        <label class="form-label">
                            Parent <?php 
                            $parentTypes = [
                                'districts' => 'Region',
                                'subcounties' => 'District',
                                'parishes' => 'Subcounty',
                                'villages' => 'Parish'
                            ];
                            echo $parentTypes[$activeTab] ?? 'Location';
                            ?>
                        </label>
                        <select class="form-select" name="parent_id" required id="parentSelect">
                            <option value="">Choose...</option>
                        </select>
                    </div>
                    <?php endif; ?>
                    
                    <div class="mb-3">
                        <label class="form-label">Name *</label>
                        <input type="text" class="form-control" name="name" required placeholder="Enter name">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Code (Optional)</label>
                        <input type="text" class="form-control" name="code" placeholder="e.g., KLA, JIN">
                        <small class="text-muted">Short code for this location</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="bi bi-x-circle me-2"></i>Cancel
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-check-circle me-2"></i>Add Location
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
const activeTab = '<?php echo $activeTab; ?>';

$(document).ready(function() {
    // Initialize DataTable
    $('#locationsTable').DataTable({
        pageLength: 25,
        order: [[1, 'asc']],
        language: {
            search: "_INPUT_",
            searchPlaceholder: "Search locations..."
        }
    });
    
    // Load parent options when modal opens
    $('#addLocationModal').on('show.bs.modal', function() {
        loadParentOptions();
    });
    
    // Handle form submission
    $('#addLocationForm').submit(function(e) {
        e.preventDefault();
        
        const btn = $(this).find('button[type="submit"]');
        btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Adding...');
        
        $.ajax({
            url: APP_URL + '/api/admin.php',
            method: 'POST',
            dataType: 'json',
            data: $(this).serialize() + '&action=add_location',
            success: function(response) {
                if (response.success) {
                    showToast(response.message, 'success');
                    $('#addLocationModal').modal('hide');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showToast(response.message, 'error');
                    btn.prop('disabled', false).html('<i class="bi bi-check-circle me-2"></i>Add Location');
                }
            },
            error: function() {
                showToast('Connection error. Please try again.', 'error');
                btn.prop('disabled', false).html('<i class="bi bi-check-circle me-2"></i>Add Location');
            }
        });
    });
});

function loadParentOptions() {
    const parentType = {
        'districts': 'regions',
        'subcounties': 'districts',
        'parishes': 'subcounties',
        'villages': 'parishes'
    }[activeTab];
    
    if (!parentType) return;
    
    $.ajax({
        url: APP_URL + '/api/locations.php',
        data: { action: 'get_' + parentType },
        success: function(response) {
            if (response.success) {
                const select = $('#parentSelect');
                select.empty().append('<option value="">Choose...</option>');
                
                response.data.forEach(item => {
                    const nameField = parentType.slice(0, -1) + '_name';
                    select.append(`<option value="${item.id}">${item[nameField]}</option>`);
                });
            }
        }
    });
}

function editLocation(id, type) {
    showToast('Edit functionality coming soon', 'info');
}

function deleteLocation(id, type) {
    Swal.fire({
        title: 'Delete Location?',
        text: 'This will also delete all child locations!',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        cancelButtonColor: '#6b7280',
        confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
        if (result.isConfirmed) {
            showLoading();
            $.ajax({
                url: APP_URL + '/api/admin.php',
                method: 'POST',
                dataType: 'json',
                data: {
                    action: 'delete_location',
                    id: id,
                    type: type
                },
                success: function(response) {
                    hideLoading();
                    if (response.success) {
                        showToast(response.message, 'success');
                        setTimeout(() => location.reload(), 1000);
                    } else {
                        showToast(response.message, 'error');
                    }
                },
                error: function() {
                    hideLoading();
                    showToast('Connection error. Please try again.', 'error');
                }
            });
        }
    });
}
</script>

<?php renderAdminFooter(); ?>