<?php
/**
 * ============================================================================
 * admin/locations.php - Location Hierarchy Management (FINAL BULLETPROOF VERSION)
 * ============================================================================
 */

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" id="openModalBtn">
        <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 if (empty($items)): ?>
                        <tr>
                            <td colspan="6" class="text-center py-4 text-muted">
                                <i class="bi bi-inbox fs-1 d-block mb-2"></i>
                                No <?php echo $activeTab; ?> found. Click "Add" to create one.
                            </td>
                        </tr>
                    <?php else: ?>
                    <?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; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add Location Modal -->
<div class="modal fade" id="addLocationModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
    <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" novalidate>
                <div class="modal-body">
                    <input type="hidden" name="type" value="<?php echo $activeTab; ?>">
                    
                    <!-- For Districts -->
                    <?php if ($activeTab === 'districts'): ?>
                        <div class="mb-3">
                            <label class="form-label">Region *</label>
                            <select class="form-select" name="parent_id" required>
                                <option value="">Select Region...</option>
                            </select>
                            <div class="invalid-feedback">Please select a region</div>
                        </div>
                    <?php endif; ?>
                    
                    <!-- For Subcounties -->
                    <?php if ($activeTab === 'subcounties'): ?>
                        <div class="mb-3">
                            <label class="form-label">Region *</label>
                            <select class="form-select" id="region_sc" required>
                                <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="district_sc" required disabled>
                                <option value="">Select District...</option>
                            </select>
                            <div class="invalid-feedback">Please select a district</div>
                        </div>
                    <?php endif; ?>
                    
                    <!-- For Parishes -->
                    <?php if ($activeTab === 'parishes'): ?>
                        <div class="mb-3">
                            <label class="form-label">Region *</label>
                            <select class="form-select" id="region_p" required>
                                <option value="">Select Region...</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">District *</label>
                            <select class="form-select" id="district_p" required disabled>
                                <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="subcounty_p" required disabled>
                                <option value="">Select Subcounty...</option>
                            </select>
                            <div class="invalid-feedback">Please select a subcounty</div>
                        </div>
                    <?php endif; ?>
                    
                    <!-- For Villages -->
                    <?php if ($activeTab === 'villages'): ?>
                        <div class="mb-3">
                            <label class="form-label">Region *</label>
                            <select class="form-select" id="region_v" required>
                                <option value="">Select Region...</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">District *</label>
                            <select class="form-select" id="district_v" required disabled>
                                <option value="">Select District...</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Subcounty *</label>
                            <select class="form-select" id="subcounty_v" required disabled>
                                <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="parish_v" required disabled>
                                <option value="">Select Parish...</option>
                            </select>
                            <div class="invalid-feedback">Please select a parish</div>
                        </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 class="invalid-feedback">Please enter a name</div>
                    </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">
                    </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" id="submitBtn">
                        <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..."
        }
    });
    
    // Open modal button
    $('#openModalBtn').click(function() {
        $('#addLocationModal').modal('show');
        loadInitialData();
    });
    
    // Cascading dropdowns for subcounties
    $('#region_sc').change(function() {
        const regionId = $(this).val();
        $('#district_sc').prop('disabled', !regionId).html('<option value="">Select District...</option>');
        if (regionId) {
            $.get(APP_URL + '/api/locations.php?action=get_districts&region_id=' + regionId, function(r) {
                if (r.success) {
                    r.data.forEach(d => $('#district_sc').append(`<option value="${d.id}">${d.district_name}</option>`));
                    $('#district_sc').prop('disabled', false);
                }
            });
        }
    });
    
    // Cascading for parishes
    $('#region_p').change(function() {
        const regionId = $(this).val();
        $('#district_p, #subcounty_p').prop('disabled', true).html('<option value="">Select...</option>');
        if (regionId) {
            $.get(APP_URL + '/api/locations.php?action=get_districts&region_id=' + regionId, function(r) {
                if (r.success) {
                    r.data.forEach(d => $('#district_p').append(`<option value="${d.id}">${d.district_name}</option>`));
                    $('#district_p').prop('disabled', false);
                }
            });
        }
    });
    
    $('#district_p').change(function() {
        const districtId = $(this).val();
        $('#subcounty_p').prop('disabled', !districtId).html('<option value="">Select Subcounty...</option>');
        if (districtId) {
            $.get(APP_URL + '/api/locations.php?action=get_subcounties&district_id=' + districtId, function(r) {
                if (r.success) {
                    r.data.forEach(s => $('#subcounty_p').append(`<option value="${s.id}">${s.subcounty_name}</option>`));
                    $('#subcounty_p').prop('disabled', false);
                }
            });
        }
    });
    
    // Cascading for villages
    $('#region_v').change(function() {
        const regionId = $(this).val();
        $('#district_v, #subcounty_v, #parish_v').prop('disabled', true).html('<option value="">Select...</option>');
        if (regionId) {
            $.get(APP_URL + '/api/locations.php?action=get_districts&region_id=' + regionId, function(r) {
                if (r.success) {
                    r.data.forEach(d => $('#district_v').append(`<option value="${d.id}">${d.district_name}</option>`));
                    $('#district_v').prop('disabled', false);
                }
            });
        }
    });
    
    $('#district_v').change(function() {
        const districtId = $(this).val();
        $('#subcounty_v, #parish_v').prop('disabled', true).html('<option value="">Select...</option>');
        if (districtId) {
            $.get(APP_URL + '/api/locations.php?action=get_subcounties&district_id=' + districtId, function(r) {
                if (r.success) {
                    r.data.forEach(s => $('#subcounty_v').append(`<option value="${s.id}">${s.subcounty_name}</option>`));
                    $('#subcounty_v').prop('disabled', false);
                }
            });
        }
    });
    
    $('#subcounty_v').change(function() {
        const subcountyId = $(this).val();
        $('#parish_v').prop('disabled', !subcountyId).html('<option value="">Select Parish...</option>');
        if (subcountyId) {
            $.get(APP_URL + '/api/locations.php?action=get_parishes&subcounty_id=' + subcountyId, function(r) {
                if (r.success) {
                    r.data.forEach(p => $('#parish_v').append(`<option value="${p.id}">${p.parish_name}</option>`));
                    $('#parish_v').prop('disabled', false);
                }
            });
        }
    });
    
    // Form submission
    $('#addLocationForm').submit(function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        if (!this.checkValidity()) {
            $(this).addClass('was-validated');
            return false;
        }
        
        const btn = $('#submitBtn');
        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',
            data: $(this).serialize() + '&action=add_location',
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    showToast(response.message, 'success');
                    setTimeout(() => location.reload(), 800);
                } else {
                    showToast(response.message, 'error');
                    btn.prop('disabled', false).html('<i class="bi bi-check-circle me-2"></i>Add Location');
                }
            },
            error: function(xhr) {
                console.error('Error:', xhr);
                showToast('Failed to add location. Please try again.', 'error');
                btn.prop('disabled', false).html('<i class="bi bi-check-circle me-2"></i>Add Location');
            }
        });
        
        return false;
    });
});

function loadInitialData() {
    if (activeTab === 'districts' || activeTab === 'subcounties' || activeTab === 'parishes' || activeTab === 'villages') {
        $.get(APP_URL + '/api/locations.php?action=get_regions', function(response) {
            if (response.success) {
                const selects = ['select[name="parent_id"]', '#region_sc', '#region_p', '#region_v'];
                selects.forEach(sel => {
                    const $select = $(sel);
                    if ($select.length) {
                        $select.html('<option value="">Select Region...</option>');
                        response.data.forEach(r => $select.append(`<option value="${r.id}">${r.region_name}</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();
            $.post(APP_URL + '/api/admin.php', {
                action: 'delete_location',
                id: id,
                type: type
            }, function(response) {
                hideLoading();
                if (response.success) {
                    showToast(response.message, 'success');
                    setTimeout(() => location.reload(), 800);
                } else {
                    showToast(response.message, 'error');
                }
            }, 'json').fail(function() {
                hideLoading();
                showToast('Connection error', 'error');
            });
        }
    });
}
</script>

<?php renderAdminFooter(); ?>