<?php
/**
 * ============================================================================
 * admin/locations.php - Location Hierarchy Management (FULLY FIXED)
 * ============================================================================
 */

require_once __DIR__ . '/includes/base.php';

$activeTab = $_GET['tab'] ?? 'regions';

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

// Fetch data based on active tab
try {
    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;
    }
} catch (PDOException $e) {
    logError('Locations fetch error: ' . $e->getMessage());
    $items = [];
}

// Get counts
$counts = [];
try {
    $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();
} catch (PDOException $e) {
    logError('Counts fetch error: ' . $e->getMessage());
    $counts = ['regions' => 0, 'districts' => 0, 'subcounties' => 0, 'parishes' => 0, 'villages' => 0];
}

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 Uganda's administrative hierarchy</p>
    </div>
    <button class="btn btn-primary" onclick="openAddModal()">
        <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 <span id="modalTitle"><?php echo ucfirst(rtrim($activeTab, 's')); ?></span>
                </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" id="locationType" value="<?php echo $activeTab; ?>">
                    
                    <!-- Hierarchical selection for nested locations -->
                    <?php if ($activeTab === 'districts'): ?>
                        <div class="mb-3">
                            <label class="form-label">Region *</label>
                            <select class="form-select" name="parent_id" id="regionSelect" required>
                                <option value="">Select Region...</option>
                            </select>
                        </div>
                    <?php elseif ($activeTab === 'subcounties'): ?>
                        <div class="mb-3">
                            <label class="form-label">Region *</label>
                            <select class="form-select" id="regionSelect2" required onchange="loadDistrictsForSubcounty(this.value)">
                                <option value="">Select Region...</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">District *</label>
                            <select class="form-select" name="parent_id" id="districtSelect" required disabled>
                                <option value="">Select District...</option>
                            </select>
                        </div>
                    <?php elseif ($activeTab === 'parishes'): ?>
                        <div class="mb-3">
                            <label class="form-label">Region *</label>
                            <select class="form-select" id="regionSelect3" required onchange="loadDistrictsForParish(this.value)">
                                <option value="">Select Region...</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">District *</label>
                            <select class="form-select" id="districtSelect2" required disabled onchange="loadSubcounties(this.value)">
                                <option value="">Select District...</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Subcounty *</label>
                            <select class="form-select" name="parent_id" id="subcountySelect" required disabled>
                                <option value="">Select Subcounty...</option>
                            </select>
                        </div>
                    <?php elseif ($activeTab === 'villages'): ?>
                        <div class="mb-3">
                            <label class="form-label">Region *</label>
                            <select class="form-select" id="regionSelect4" required onchange="loadDistrictsForVillage(this.value)">
                                <option value="">Select Region...</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">District *</label>
                            <select class="form-select" id="districtSelect3" required disabled onchange="loadSubcountiesForVillage(this.value)">
                                <option value="">Select District...</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Subcounty *</label>
                            <select class="form-select" id="subcountySelect2" required disabled onchange="loadParishes(this.value)">
                                <option value="">Select Subcounty...</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Parish *</label>
                            <select class="form-select" name="parent_id" id="parishSelect" required disabled>
                                <option value="">Select Parish...</option>
                            </select>
                        </div>
                    <?php endif; ?>
                    
                    <div class="mb-3">
                        <label class="form-label">Name *</label>
                        <input type="text" class="form-control" name="name" id="locationName" required placeholder="Enter name">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Code (Optional)</label>
                        <input type="text" class="form-control" name="code" id="locationCode" 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>
// Variables must be declared BEFORE document.ready
const activeTab = '<?php echo $activeTab; ?>';

// Wait for document ready
$(document).ready(function() {
    console.log('Page loaded. Active tab:', activeTab);
    
    // Initialize DataTable
    $('#locationsTable').DataTable({
        pageLength: 25,
        order: [[1, 'asc']],
        language: {
            search: "_INPUT_",
            searchPlaceholder: "Search locations..."
        }
    });
});

function openAddModal() {
    console.log('Opening modal for:', activeTab);
    $('#addLocationModal').modal('show');
    
    // Load initial data based on tab
    if (activeTab === 'districts') {
        loadRegionsForDistrict();
    } else if (activeTab === 'subcounties') {
        loadRegionsForSubcounty();
    } else if (activeTab === 'parishes') {
        loadRegionsForParish();
    } else if (activeTab === 'villages') {
        loadRegionsForVillage();
    }
}

// Load regions for district
function loadRegionsForDistrict() {
    $.get(APP_URL + '/api/locations.php?action=get_regions', function(response) {
        if (response.success) {
            const select = $('#regionSelect');
            select.empty().append('<option value="">Select Region...</option>');
            response.data.forEach(region => {
                select.append(`<option value="${region.id}">${region.region_name}</option>`);
            });
        }
    });
}

// Load regions for subcounty
function loadRegionsForSubcounty() {
    $.get(APP_URL + '/api/locations.php?action=get_regions', function(response) {
        if (response.success) {
            const select = $('#regionSelect2');
            select.empty().append('<option value="">Select Region...</option>');
            response.data.forEach(region => {
                select.append(`<option value="${region.id}">${region.region_name}</option>`);
            });
        }
    });
}

// Load districts for subcounty
function loadDistrictsForSubcounty(regionId) {
    const select = $('#districtSelect');
    select.prop('disabled', !regionId).empty().append('<option value="">Select District...</option>');
    
    if (regionId) {
        $.get(APP_URL + '/api/locations.php?action=get_districts&region_id=' + regionId, function(response) {
            if (response.success) {
                response.data.forEach(district => {
                    select.append(`<option value="${district.id}">${district.district_name}</option>`);
                });
            }
        });
    }
}

// Load regions for parish
function loadRegionsForParish() {
    $.get(APP_URL + '/api/locations.php?action=get_regions', function(response) {
        if (response.success) {
            const select = $('#regionSelect3');
            select.empty().append('<option value="">Select Region...</option>');
            response.data.forEach(region => {
                select.append(`<option value="${region.id}">${region.region_name}</option>`);
            });
        }
    });
}

// Load districts for parish
function loadDistrictsForParish(regionId) {
    const select = $('#districtSelect2');
    select.prop('disabled', !regionId).empty().append('<option value="">Select District...</option>');
    $('#subcountySelect').prop('disabled', true).empty().append('<option value="">Select Subcounty...</option>');
    
    if (regionId) {
        $.get(APP_URL + '/api/locations.php?action=get_districts&region_id=' + regionId, function(response) {
            if (response.success) {
                response.data.forEach(district => {
                    select.append(`<option value="${district.id}">${district.district_name}</option>`);
                });
            }
        });
    }
}

// Load subcounties
function loadSubcounties(districtId) {
    const select = $('#subcountySelect');
    select.prop('disabled', !districtId).empty().append('<option value="">Select Subcounty...</option>');
    
    if (districtId) {
        $.get(APP_URL + '/api/locations.php?action=get_subcounties&district_id=' + districtId, function(response) {
            if (response.success) {
                response.data.forEach(subcounty => {
                    select.append(`<option value="${subcounty.id}">${subcounty.subcounty_name}</option>`);
                });
            }
        });
    }
}

// Load regions for village
function loadRegionsForVillage() {
    $.get(APP_URL + '/api/locations.php?action=get_regions', function(response) {
        if (response.success) {
            const select = $('#regionSelect4');
            select.empty().append('<option value="">Select Region...</option>');
            response.data.forEach(region => {
                select.append(`<option value="${region.id}">${region.region_name}</option>`);
            });
        }
    });
}

// Load districts for village
function loadDistrictsForVillage(regionId) {
    const select = $('#districtSelect3');
    select.prop('disabled', !regionId).empty().append('<option value="">Select District...</option>');
    $('#subcountySelect2').prop('disabled', true).empty().append('<option value="">Select Subcounty...</option>');
    $('#parishSelect').prop('disabled', true).empty().append('<option value="">Select Parish...</option>');
    
    if (regionId) {
        $.get(APP_URL + '/api/locations.php?action=get_districts&region_id=' + regionId, function(response) {
            if (response.success) {
                response.data.forEach(district => {
                    select.append(`<option value="${district.id}">${district.district_name}</option>`);
                });
            }
        });
    }
}

// Load subcounties for village
function loadSubcountiesForVillage(districtId) {
    const select = $('#subcountySelect2');
    select.prop('disabled', !districtId).empty().append('<option value="">Select Subcounty...</option>');
    $('#parishSelect').prop('disabled', true).empty().append('<option value="">Select Parish...</option>');
    
    if (districtId) {
        $.get(APP_URL + '/api/locations.php?action=get_subcounties&district_id=' + districtId, function(response) {
            if (response.success) {
                response.data.forEach(subcounty => {
                    select.append(`<option value="${subcounty.id}">${subcounty.subcounty_name}</option>`);
                });
            }
        });
    }
}

// Load parishes
function loadParishes(subcountyId) {
    const select = $('#parishSelect');
    select.prop('disabled', !subcountyId).empty().append('<option value="">Select Parish...</option>');
    
    if (subcountyId) {
        $.get(APP_URL + '/api/locations.php?action=get_parishes&subcounty_id=' + subcountyId, function(response) {
            if (response.success) {
                response.data.forEach(parish => {
                    select.append(`<option value="${parish.id}">${parish.parish_name}</option>`);
                });
            }
        });
    }
}

// Handle form submission
$('#addLocationForm').submit(function(e) {
    e.preventDefault();
    
    if (!this.checkValidity()) {
        e.stopPropagation();
        $(this).addClass('was-validated');
        return;
    }
    
    const btn = $(this).find('button[type="submit"]');
    const originalHtml = btn.html();
    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(originalHtml);
            }
        },
        error: function(xhr) {
            console.error('Error:', xhr.responseText);
            showToast('Connection error. Please try again.', 'error');
            btn.prop('disabled', false).html(originalHtml);
        }
    });
});

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(); ?>