Sindbad~EG File Manager

Current Path : /home/copmadinaarea/thecopmadinaarea.org/attendance/admin/
Upload File :
Current File : /home/copmadinaarea/thecopmadinaarea.org/attendance/admin/locations.php

<?php
require_once '../config/config.php';

// Check if user is logged in
if (!isLoggedIn()) {
    redirect('login.php');
}

$db = new Database();
$conn = $db->getConnection();

$success_message = '';
$error_message = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validateCSRFToken($_POST['csrf_token'] ?? '')) {
        $error_message = 'Invalid security token. Please try again.';
    } else {
        $action = $_POST['action'] ?? '';
        
        if ($action === 'create' || $action === 'update') {
            $name = sanitizeInput($_POST['name'] ?? '');
            $type = $_POST['type'] ?? '';
            $parent_id = $_POST['parent_id'] ?? null;
            $address = sanitizeInput($_POST['address'] ?? '');
            $contact_person = sanitizeInput($_POST['contact_person'] ?? '');
            $contact_phone = sanitizeInput($_POST['contact_phone'] ?? '');
            $contact_email = sanitizeInput($_POST['contact_email'] ?? '');
            $is_active = isset($_POST['is_active']) ? 1 : 0;
            
            if (empty($name) || empty($type)) {
                $error_message = 'Location name and type are required.';
            } else {
                try {
                    if ($action === 'create') {
                        $query = "INSERT INTO locations (name, type, parent_id, address, contact_person, contact_phone, contact_email, is_active) 
                                  VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
                        $stmt = $conn->prepare($query);
                        $stmt->execute([$name, $type, $parent_id ?: null, $address, $contact_person, $contact_phone, $contact_email, $is_active]);
                        
                        logActivity($_SESSION['user_id'], 'create_location', "Created location: $name");
                        $success_message = 'Location created successfully.';
                    } else {
                        $location_id = (int)$_POST['location_id'];
                        $query = "UPDATE locations SET name = ?, type = ?, parent_id = ?, address = ?, contact_person = ?, contact_phone = ?, contact_email = ?, is_active = ? 
                                  WHERE id = ?";
                        $stmt = $conn->prepare($query);
                        $stmt->execute([$name, $type, $parent_id ?: null, $address, $contact_person, $contact_phone, $contact_email, $is_active, $location_id]);
                        
                        logActivity($_SESSION['user_id'], 'update_location', "Updated location: $name");
                        $success_message = 'Location updated successfully.';
                    }
                } catch (Exception $e) {
                    $error_message = 'An error occurred while saving the location.';
                }
            }
        } elseif ($action === 'delete' && hasRole('superuser')) {
            $location_id = (int)$_POST['location_id'];
            
            try {
                $query = "DELETE FROM locations WHERE id = ?";
                $stmt = $conn->prepare($query);
                $stmt->execute([$location_id]);
                
                logActivity($_SESSION['user_id'], 'delete_location', "Deleted location ID: $location_id");
                $success_message = 'Location deleted successfully.';
            } catch (Exception $e) {
                $error_message = 'Cannot delete location. It may have associated programs or users.';
            }
        }
    }
}

// Get locations with parent information and usage statistics
$query = "SELECT l.*, p.name as parent_name,
                 COUNT(DISTINCT CASE WHEN ar.district_id = l.id THEN ar.id END) as district_usage,
                 COUNT(DISTINCT CASE WHEN ar.assembly_id = l.id THEN ar.id END) as assembly_usage,
                 COUNT(DISTINCT CASE WHEN pr.location_id = l.id THEN pr.id END) as program_usage,
                 COUNT(DISTINCT CASE WHEN child.parent_id = l.id THEN child.id END) as child_locations
          FROM locations l 
          LEFT JOIN locations p ON l.parent_id = p.id 
          LEFT JOIN attendance_records ar ON (ar.district_id = l.id OR ar.assembly_id = l.id)
          LEFT JOIN programs pr ON pr.location_id = l.id
          LEFT JOIN locations child ON child.parent_id = l.id
          GROUP BY l.id
          ORDER BY l.type, l.name";
$stmt = $conn->prepare($query);
$stmt->execute();
$locations = $stmt->fetchAll();

// Get districts for dropdown
$districts_query = "SELECT id, name FROM locations WHERE type = 'district' AND is_active = 1 ORDER BY name";
$districts_stmt = $conn->prepare($districts_query);
$districts_stmt->execute();
$districts = $districts_stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Locations - Admin Panel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#F59E0B',
                        accent: '#6B7280'
                    }
                }
            }
        }
    </script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .gradient-bg {
            background: linear-gradient(135deg, #3B82F6 0%, #F59E0B 50%, #6B7280 100%);
        }
    </style>
</head>
<body class="bg-gray-50">
    <!-- Include Sidebar -->
    <?php include 'includes/sidebar.php'; ?>

    <!-- Main Content -->
    <div class="md:ml-64">
        <!-- Header -->
        <header class="bg-white shadow-sm border-b">
            <div class="px-6 py-4">
                <div class="flex items-center justify-between">
                    <h1 class="text-2xl font-bold text-gray-900">Location Management</h1>
                    <?php if (hasRole('superuser')): ?>
                        <button onclick="showCreateModal()" class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition duration-300">
                            <i class="fas fa-plus mr-2"></i>
                            Add Location
                        </button>
                    <?php endif; ?>
                </div>
            </div>
        </header>

        <!-- Content -->
        <main class="p-6">
            <!-- Success/Error Messages -->
            <?php if ($success_message): ?>
                <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-6">
                    <div class="flex items-center">
                        <i class="fas fa-check-circle mr-2"></i>
                        <span><?php echo $success_message; ?></span>
                    </div>
                </div>
            <?php endif; ?>

            <?php if ($error_message): ?>
                <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6">
                    <div class="flex items-center">
                        <i class="fas fa-exclamation-circle mr-2"></i>
                        <span><?php echo $error_message; ?></span>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Locations Table -->
            <div class="bg-white rounded-lg shadow overflow-hidden">
                <div class="px-6 py-4 border-b">
                    <h3 class="text-lg font-semibold text-gray-900">
                        <i class="fas fa-map-marker-alt mr-2"></i>
                        Church Locations
                    </h3>
                </div>

                <?php if (empty($locations)): ?>
                    <div class="text-center py-12">
                        <i class="fas fa-map-marker-alt text-6xl text-gray-400 mb-4"></i>
                        <h3 class="text-xl font-semibold text-gray-700 mb-2">No Locations Found</h3>
                        <p class="text-gray-500 mb-4">Start by adding your first district or assembly.</p>
                        <?php if (hasRole('superuser')): ?>
                            <button onclick="showCreateModal()" class="bg-primary text-white px-6 py-2 rounded-lg hover:bg-blue-700 transition duration-300">
                                <i class="fas fa-plus mr-2"></i>
                                Add Location
                            </button>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Location
                                    </th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Type
                                    </th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Parent
                                    </th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Contact
                                    </th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Programs
                                    </th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Status
                                    </th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Actions
                                    </th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                <?php foreach ($locations as $location): ?>
                                    <tr class="hover:bg-gray-50">
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <div>
                                                <div class="text-sm font-medium text-gray-900">
                                                    <?php echo htmlspecialchars($location['name']); ?>
                                                </div>
                                                <?php if ($location['address']): ?>
                                                    <div class="text-sm text-gray-500">
                                                        <?php echo htmlspecialchars($location['address']); ?>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium <?php echo $location['type'] === 'district' ? 'bg-blue-100 text-blue-800' : 'bg-green-100 text-green-800'; ?>">
                                                <i class="fas <?php echo $location['type'] === 'district' ? 'fa-building' : 'fa-home'; ?> mr-1"></i>
                                                <?php echo ucfirst($location['type']); ?>
                                            </span>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                            <?php echo htmlspecialchars($location['parent_name'] ?? 'None'); ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <?php if ($location['contact_person']): ?>
                                                <div class="text-sm text-gray-900">
                                                    <i class="fas fa-user mr-1"></i>
                                                    <?php echo htmlspecialchars($location['contact_person']); ?>
                                                </div>
                                            <?php endif; ?>
                                            <?php if ($location['contact_phone']): ?>
                                                <div class="text-sm text-gray-500">
                                                    <i class="fas fa-phone mr-1"></i>
                                                    <?php echo htmlspecialchars($location['contact_phone']); ?>
                                                </div>
                                            <?php endif; ?>
                                            <?php if ($location['contact_email']): ?>
                                                <div class="text-sm text-gray-500">
                                                    <i class="fas fa-envelope mr-1"></i>
                                                    <?php echo htmlspecialchars($location['contact_email']); ?>
                                                </div>
                                            <?php endif; ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                            <div class="flex items-center">
                                                <i class="fas fa-calendar mr-1"></i>
                                                <?php echo number_format($location['program_usage'] ?? 0); ?>
                                            </div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium <?php echo $location['is_active'] ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'; ?>">
                                                <?php echo $location['is_active'] ? 'Active' : 'Inactive'; ?>
                                            </span>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                            <div class="flex space-x-2">
                                                <?php if (hasRole('superuser')): ?>
                                                    <button onclick="editLocation(<?php echo $location['id']; ?>)" 
                                                            class="text-primary hover:text-blue-700">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <button onclick="deleteLocation(<?php echo $location['id']; ?>)" 
                                                            class="text-red-600 hover:text-red-900">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                <?php endif; ?>
                                                <a href="programs.php?location=<?php echo $location['id']; ?>" 
                                                   class="text-green-600 hover:text-green-900">
                                                    <i class="fas fa-eye"></i>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </main>
    </div>

    <!-- Create/Edit Location Modal -->
    <?php if (hasRole('superuser')): ?>
    <div id="locationModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden items-center justify-center z-50">
        <div class="bg-white rounded-lg p-6 max-w-lg w-full mx-4">
            <div class="flex items-center justify-between mb-4">
                <h3 id="modalTitle" class="text-lg font-semibold text-gray-900">Add Location</h3>
                <button onclick="closeModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <form method="POST" id="locationForm">
                <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                <input type="hidden" name="action" id="formAction" value="create">
                <input type="hidden" name="location_id" id="locationId">
                
                <div class="space-y-4">
                    <div>
                        <label for="name" class="block text-sm font-medium text-gray-700 mb-2">
                            Location Name <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="name" name="name" required
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                    </div>
                    
                    <div>
                        <label for="type" class="block text-sm font-medium text-gray-700 mb-2">
                            Type <span class="text-red-500">*</span>
                        </label>
                        <select id="type" name="type" required onchange="toggleParentField()"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                            <option value="">Select Type</option>
                            <option value="district">District</option>
                            <option value="assembly">Assembly</option>
                        </select>
                    </div>
                    
                    <div id="parentField" class="hidden">
                        <label for="parent_id" class="block text-sm font-medium text-gray-700 mb-2">
                            Parent District
                        </label>
                        <select id="parent_id" name="parent_id"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                            <option value="">Select District</option>
                            <?php foreach ($districts as $district): ?>
                                <option value="<?php echo $district['id']; ?>">
                                    <?php echo htmlspecialchars($district['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div>
                        <label for="address" class="block text-sm font-medium text-gray-700 mb-2">
                            Address
                        </label>
                        <textarea id="address" name="address" rows="2"
                                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"></textarea>
                    </div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label for="contact_person" class="block text-sm font-medium text-gray-700 mb-2">
                                Contact Person
                            </label>
                            <input type="text" id="contact_person" name="contact_person"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                        </div>
                        
                        <div>
                            <label for="contact_phone" class="block text-sm font-medium text-gray-700 mb-2">
                                Contact Phone
                            </label>
                            <input type="tel" id="contact_phone" name="contact_phone"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                        </div>
                    </div>
                    
                    <div>
                        <label for="contact_email" class="block text-sm font-medium text-gray-700 mb-2">
                            Contact Email
                        </label>
                        <input type="email" id="contact_email" name="contact_email"
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                    </div>
                    
                    <div class="flex items-center">
                        <input type="checkbox" id="is_active" name="is_active" checked
                               class="h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded">
                        <label for="is_active" class="ml-2 block text-sm text-gray-700">
                            Active
                        </label>
                    </div>
                </div>
                
                <div class="flex justify-end space-x-4 mt-6">
                    <button type="button" onclick="closeModal()" 
                            class="px-4 py-2 text-gray-600 hover:text-gray-800">
                        Cancel
                    </button>
                    <button type="submit" 
                            class="px-4 py-2 bg-primary text-white rounded hover:bg-blue-700">
                        <span id="submitText">Add Location</span>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div id="deleteModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden items-center justify-center z-50">
        <div class="bg-white rounded-lg p-6 max-w-sm mx-auto">
            <h3 class="text-lg font-semibold text-gray-900 mb-4">Confirm Delete</h3>
            <p class="text-gray-600 mb-6">Are you sure you want to delete this location? This action cannot be undone.</p>
            <div class="flex justify-end space-x-4">
                <button onclick="closeDeleteModal()" class="px-4 py-2 text-gray-600 hover:text-gray-800">
                    Cancel
                </button>
                <form method="POST" id="deleteForm" class="inline">
                    <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="location_id" id="deleteId">
                    <button type="submit" class="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700">
                        Delete
                    </button>
                </form>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <script>
        function toggleParentField() {
            const type = document.getElementById('type').value;
            const parentField = document.getElementById('parentField');
            
            if (type === 'assembly') {
                parentField.classList.remove('hidden');
            } else {
                parentField.classList.add('hidden');
                document.getElementById('parent_id').value = '';
            }
        }

        function showCreateModal() {
            document.getElementById('modalTitle').textContent = 'Add Location';
            document.getElementById('formAction').value = 'create';
            document.getElementById('submitText').textContent = 'Add Location';
            document.getElementById('locationForm').reset();
            document.getElementById('is_active').checked = true;
            document.getElementById('parentField').classList.add('hidden');
            document.getElementById('locationModal').classList.remove('hidden');
            document.getElementById('locationModal').classList.add('flex');
        }

        function editLocation(id) {
            // Fetch location data via AJAX
            fetch('get_location_details.php?id=' + id)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const location = data.location;
                        
                        // Populate form fields
                        document.getElementById('modalTitle').textContent = 'Edit Location';
                        document.getElementById('formAction').value = 'update';
                        document.getElementById('submitText').textContent = 'Update Location';
                        document.getElementById('locationId').value = location.id;
                        document.getElementById('name').value = location.name;
                        document.getElementById('type').value = location.type;
                        document.getElementById('address').value = location.address || '';
                        document.getElementById('contact_person').value = location.contact_person || '';
                        document.getElementById('contact_phone').value = location.contact_phone || '';
                        document.getElementById('contact_email').value = location.contact_email || '';
                        document.getElementById('is_active').checked = location.is_active == 1;
                        
                        // Handle parent field
                        if (location.type === 'assembly') {
                            document.getElementById('parentField').classList.remove('hidden');
                            document.getElementById('parent_id').value = location.parent_id || '';
                        } else {
                            document.getElementById('parentField').classList.add('hidden');
                        }
                        
                        // Show modal
                        document.getElementById('locationModal').classList.remove('hidden');
                        document.getElementById('locationModal').classList.add('flex');
                    } else {
                        alert('Error loading location data: ' + data.message);
                    }
                })
                .catch(error => {
                    alert('Error loading location data');
                    console.error('Error:', error);
                });
        }

        function deleteLocation(id) {
            document.getElementById('deleteId').value = id;
            document.getElementById('deleteModal').classList.remove('hidden');
            document.getElementById('deleteModal').classList.add('flex');
        }

        function closeModal() {
            document.getElementById('locationModal').classList.add('hidden');
            document.getElementById('locationModal').classList.remove('flex');
        }

        function closeDeleteModal() {
            document.getElementById('deleteModal').classList.add('hidden');
            document.getElementById('deleteModal').classList.remove('flex');
        }

        // Close modals when clicking outside
        document.getElementById('locationModal')?.addEventListener('click', function(e) {
            if (e.target === this) closeModal();
        });

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

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists