Sindbad~EG File Manager

Current Path : /home/copmadinaarea/thecopmadinaarea.org/portal/modules/administration/
Upload File :
Current File : /home/copmadinaarea/thecopmadinaarea.org/portal/modules/administration/districts.php

<?php
require_once '../../config/config.php';
checkLogin();
require_once '../../classes/AuditLog.php';

// District management requires area level access or higher
checkAccess('district');

$pageTitle = "Districts Management - " . APP_NAME;
$db = Database::getInstance()->getConnection();

$success = '';
$error = '';

// Handle PDF Export
if (isset($_GET['action']) && $_GET['action'] == 'export_pdf') {
    require_once '../../vendor/autoload.php';
    
    // Get all districts with area name
    $districtsStmt = $db->query("
        SELECT d.*, a.area_name, a.area_code,
               (SELECT COUNT(*) FROM assemblies WHERE district_id = d.id) as assembly_count
        FROM districts d
        JOIN areas a ON d.area_id = a.id
        ORDER BY a.area_name, d.district_name
    ");
    $districts = $districtsStmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Create PDF
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
    
    $pdf->SetCreator(PDF_CREATOR);
    $pdf->SetAuthor(APP_NAME);
    $pdf->SetTitle('Districts Reference List');
    $pdf->SetSubject('Complete list of districts with reference codes');
    
    $pdf->setPrintHeader(false);
    $pdf->setPrintFooter(false);
    $pdf->SetMargins(15, 15, 15);
    $pdf->SetAutoPageBreak(TRUE, 15);
    $pdf->AddPage();
    
    // Title
    $pdf->SetFont('helvetica', 'B', 16);
    $pdf->Cell(0, 10, APP_NAME, 0, 1, 'C');
    $pdf->SetFont('helvetica', 'B', 14);
    $pdf->Cell(0, 10, 'Districts Reference List', 0, 1, 'C');
    $pdf->SetFont('helvetica', '', 10);
    $pdf->Cell(0, 5, 'Generated: ' . date('F d, Y - h:i A'), 0, 1, 'C');
    $pdf->Ln(5);
    
    // Summary
    $pdf->SetFont('helvetica', 'B', 11);
    $pdf->Cell(0, 7, 'Total Districts: ' . count($districts), 0, 1);
    $pdf->Ln(3);
    
    // Table header
    $pdf->SetFont('helvetica', 'B', 9);
    $pdf->SetFillColor(30, 64, 175);
    $pdf->SetTextColor(255, 255, 255);
    
    $pdf->Cell(10, 7, '#', 1, 0, 'C', true);
    $pdf->Cell(30, 7, 'Area Code', 1, 0, 'C', true);
    $pdf->Cell(35, 7, 'District Code', 1, 0, 'C', true);
    $pdf->Cell(50, 7, 'District Name', 1, 0, 'C', true);
    $pdf->Cell(25, 7, 'Assemblies', 1, 0, 'C', true);
    $pdf->Cell(20, 7, 'Status', 1, 0, 'C', true);
    $pdf->Cell(20, 7, 'Active', 1, 1, 'C', true);
    
    // Table content
    $pdf->SetFont('helvetica', '', 8);
    $pdf->SetTextColor(0, 0, 0);
    
    $num = 1;
    foreach ($districts as $district) {
        $fillColor = $district['is_active'] ? [240, 253, 244] : [254, 242, 242];
        $pdf->SetFillColor($fillColor[0], $fillColor[1], $fillColor[2]);
        
        $pdf->Cell(10, 6, $num++, 1, 0, 'C', true);
        $pdf->Cell(30, 6, $district['area_code'], 1, 0, 'C', true);
        $pdf->Cell(35, 6, $district['district_code'], 1, 0, 'C', true);
        $pdf->Cell(50, 6, substr($district['district_name'], 0, 30), 1, 0, 'L', true);
        $pdf->Cell(25, 6, $district['assembly_count'], 1, 0, 'C', true);
        $pdf->Cell(20, 6, substr($district['area_name'], 0, 12), 1, 0, 'L', true);
        $pdf->Cell(20, 6, $district['is_active'] ? 'Yes' : 'No', 1, 1, 'C', true);
    }

// Handle ACTIVATE/DEACTIVATE with cascading
if (isset($_GET['toggle_active']) && isset($_GET['id'])) {
    $districtId = (int)$_GET['id'];
    $targetStatus = (int)$_GET['toggle_active']; // 1 = activate, 0 = deactivate

    try {
        $db->beginTransaction();

        // Update district status
        $stmt = $db->prepare("UPDATE districts SET is_active = :status WHERE id = :id");
        $stmt->execute(['status' => $targetStatus, 'id' => $districtId]);

        if ($targetStatus === 0) {
            // Deactivate all assemblies and members under this district
            $stmt = $db->prepare("UPDATE assemblies SET is_active = 0 WHERE district_id = :district_id");
            $stmt->execute(['district_id' => $districtId]);

            $stmt = $db->prepare("UPDATE members SET is_active = 0 WHERE district_id = :district_id");
            $stmt->execute(['district_id' => $districtId]);
        }

        $db->commit();

        $auditLog = new AuditLog();
        $auditLog->log($_SESSION['user_id'], $targetStatus === 1 ? 'activate' : 'deactivate', 'districts', $districtId);

        $success = $targetStatus === 1
            ? "District activated successfully!"
            : "District and all related assemblies and members deactivated successfully!";
    } catch (PDOException $e) {
        $db->rollBack();
        $error = "Error updating district status: " . $e->getMessage();
    }
}
    
    $filename = 'districts_reference_' . date('Ymd_His') . '.pdf';
    $pdf->Output($filename, 'D');
    exit;
}

// Handle Admin Assignment
if (isset($_POST['assign_admin'])) {
    try {
        $stmt = $db->prepare("
            INSERT IGNORE INTO admin_location_assignments 
            (user_id, location_type, district_id, assigned_by) 
            VALUES (:user_id, 'district', :district_id, :assigned_by)
        ");
        $stmt->execute([
            'user_id' => $_POST['user_id'],
            'district_id' => $_POST['location_id'],
            'assigned_by' => $_SESSION['user_id']
        ]);
        $success = "Admin assigned successfully!";
    } catch (PDOException $e) {
        $error = "Error assigning admin: " . $e->getMessage();
    }
}

// Handle Remove Assignment
if (isset($_GET['remove_assignment'])) {
    try {
        $stmt = $db->prepare("DELETE FROM admin_location_assignments WHERE id = :id");
        $stmt->execute(['id' => $_GET['remove_assignment']]);
        $success = "Assignment removed successfully!";
    } catch (PDOException $e) {
        $error = "Error removing assignment";
    }
}

// Handle DELETE
if (isset($_GET['delete'])) {
    try {
        $stmt = $db->prepare("DELETE FROM districts WHERE id = :id");
        $stmt->execute(['id' => $_GET['delete']]);
        $success = "District deleted successfully!";
        
        $auditLog = new AuditLog();
        $auditLog->log($_SESSION['user_id'], 'delete', 'districts', $_GET['delete']);
    } catch (PDOException $e) {
        $error = "Cannot delete district: This district has associated assemblies.";
    }
}

// Handle UPDATE
if (isset($_POST['update_district'])) {
    try {
        $stmt = $db->prepare("
            UPDATE districts 
            SET area_id = :area_id, district_name = :name, district_code = :code, description = :description,
                contact_person = :contact, phone = :phone, email = :email, address = :address
            WHERE id = :id
        ");
        
        $stmt->execute([
            'area_id' => $_POST['area_id'],
            'name' => $_POST['district_name'],
            'code' => strtoupper($_POST['district_code']),
            'description' => $_POST['description'] ?: null,
            'contact' => $_POST['contact_person'] ?: null,
            'phone' => $_POST['phone'] ?: null,
            'email' => $_POST['email'] ?: null,
            'address' => $_POST['address'] ?: null,
            'id' => $_POST['district_id']
        ]);
        
        $auditLog = new AuditLog();
        $auditLog->log($_SESSION['user_id'], 'update', 'districts', $_POST['district_id']);
        
        $success = "District updated successfully!";
    } catch (PDOException $e) {
        $error = "Error: " . $e->getMessage();
    }
}

// Handle ADD
if (isset($_POST['add_district'])) {
    try {
        // Check if district_code already exists
        $checkStmt = $db->prepare("SELECT d.id, d.district_name, a.area_name FROM districts d JOIN areas a ON d.area_id = a.id WHERE d.district_code = :code");
        $checkStmt->execute(['code' => strtoupper($_POST['district_code'])]);
        $existing = $checkStmt->fetch();
        
        if ($existing) {
            $error = "⚠️ District with code '" . htmlspecialchars(strtoupper($_POST['district_code'])) . "' already exists (Name: " . htmlspecialchars($existing['district_name']) . " in " . htmlspecialchars($existing['area_name']) . "). Please use a different code.";
        } else {
            // Check if district_name already exists in the same area
            $checkNameStmt = $db->prepare("SELECT d.id, d.district_code FROM districts d WHERE d.district_name = :name AND d.area_id = :area_id");
            $checkNameStmt->execute(['name' => $_POST['district_name'], 'area_id' => $_POST['area_id']]);
            $existingName = $checkNameStmt->fetch();
            
            if ($existingName) {
                $error = "⚠️ District with name '" . htmlspecialchars($_POST['district_name']) . "' already exists in this area (Code: " . htmlspecialchars($existingName['district_code']) . "). Please use a different name.";
            } else {
                $stmt = $db->prepare("
                    INSERT INTO districts (area_id, district_name, district_code, description, contact_person, phone, email, address)
                    VALUES (:area_id, :name, :code, :description, :contact, :phone, :email, :address)
                ");
                
                $stmt->execute([
                    'area_id' => $_POST['area_id'],
                    'name' => $_POST['district_name'],
                    'code' => strtoupper($_POST['district_code']),
                    'description' => $_POST['description'] ?: null,
                    'contact' => $_POST['contact_person'] ?: null,
                    'phone' => $_POST['phone'] ?: null,
                    'email' => $_POST['email'] ?: null,
                    'address' => $_POST['address'] ?: null
                ]);
                
                $auditLog = new AuditLog();
                $auditLog->log($_SESSION['user_id'], 'create', 'districts', $db->lastInsertId());
                
                $success = "✅ District added successfully!";
            }
        }
    } catch (PDOException $e) {
        $error = "Error: " . $e->getMessage();
    }
}

// Get all districts with area name and assembly counts
$districtsStmt = $db->query("
    SELECT d.*, a.area_name,
           (SELECT COUNT(*) FROM assemblies WHERE district_id = d.id) as assembly_count
    FROM districts d
    JOIN areas a ON d.area_id = a.id
    ORDER BY a.area_name, d.district_name
");
$districts = $districtsStmt->fetchAll();

// Get all areas for dropdowns
$areasStmt = $db->query("SELECT id, area_name, area_code FROM areas WHERE is_active = 1 ORDER BY area_name");
$areas = $areasStmt->fetchAll();

// Get all users for assignment
$usersStmt = $db->query("SELECT id, full_name, email, access_level FROM users WHERE is_active = 1 ORDER BY full_name");
$users = $usersStmt->fetchAll();

include '../../includes/header.php';
?>

<?php include '../../includes/sidebar.php'; ?>

<main class="flex-1 md:ml-64 mt-16">
<div class="container mx-auto px-4 py-8">
    <!-- Header -->
    <div class="gradient-bg rounded-2xl shadow-2xl p-8 mb-8 text-white">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-4xl font-bold mb-2">
                    <i class="fas fa-map-marker-alt mr-3"></i>Districts Management
                </h1>
                <p class="text-white/90 text-lg">Manage church districts and assign administrators</p>
            </div>
            <div class="flex flex-wrap gap-3">
                <button onclick="document.getElementById('addModal').classList.remove('hidden')" 
                        class="btn-gradient-orange text-white px-8 py-3 rounded-full font-bold shadow-lg hover:shadow-xl transition">
                    <i class="fas fa-plus mr-2"></i>Add New District
                </button>
                <a href="upload-locations.php" 
                   class="btn-gradient text-white px-8 py-3 rounded-full font-bold shadow-lg hover:shadow-xl transition inline-block">
                    <i class="fas fa-upload mr-2"></i>Bulk Upload
                </a>
                <a href="?action=export_pdf" 
                   class="bg-red-600 hover:bg-red-700 text-white px-8 py-3 rounded-full font-bold shadow-lg hover:shadow-xl transition inline-block">
                    <i class="fas fa-file-pdf mr-2"></i>Export PDF
                </a>
            </div>
        </div>
    </div>
    
    <?php if ($success): ?>
        <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-6 rounded-lg mb-6 animate-fadeIn">
            <i class="fas fa-check-circle mr-2"></i><?php echo $success; ?>
        </div>
    <?php endif; ?>
    
    <?php if ($error): ?>
        <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-6 rounded-lg mb-6">
            <i class="fas fa-exclamation-circle mr-2"></i><?php echo $error; ?>
        </div>
    <?php endif; ?>
    
    <!-- Districts Grid -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <?php foreach ($districts as $district): 
            // Get assigned admins
            $adminStmt = $db->prepare("
                SELECT ala.id as assignment_id, u.full_name, u.email 
                FROM admin_location_assignments ala
                JOIN users u ON ala.user_id = u.id
                WHERE ala.location_type = 'district' AND ala.district_id = ? AND ala.is_active = 1
            ");
            $adminStmt->execute([$district['id']]);
            $assignedAdmins = $adminStmt->fetchAll();
        ?>
            <div class="bg-white rounded-2xl shadow-lg p-6 hover:shadow-2xl transition border-t-4" style="border-top-color: #F97316;">
                <div class="flex items-start justify-between mb-4">
                    <div class="flex items-center">
                        <div class="rounded-full p-3 mr-3 gradient-secondary">
                            <i class="fas fa-map-marker-alt text-white text-xl"></i>
                        </div>
                        <div>
                            <h3 class="font-bold text-lg text-gray-800"><?php echo htmlspecialchars($district['district_name']); ?></h3>
                            <span class="text-sm bg-orange-100 text-orange-800 px-2 py-1 rounded font-mono">
                                <?php echo htmlspecialchars($district['district_code']); ?>
                            </span>
                        </div>
                    </div>
                    <span class="px-3 py-1 text-xs font-semibold rounded-full <?php echo $district['is_active'] ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
                        <?php echo $district['is_active'] ? 'Active' : 'Inactive'; ?>
                    </span>
                </div>
                
                <!-- Area Badge -->
                <div class="mb-4">
                    <span class="inline-flex items-center text-sm bg-blue-100 text-blue-800 px-3 py-1 rounded-full">
                        <i class="fas fa-map-marked-alt mr-2"></i><?php echo htmlspecialchars($district['area_name']); ?>
                    </span>
                </div>
                
                <?php if ($district['description']): ?>
                    <p class="text-gray-600 text-sm mb-4"><?php echo htmlspecialchars($district['description']); ?></p>
                <?php endif; ?>
                
                <div class="space-y-2 text-sm text-gray-600 mb-4">
                    <?php if ($district['contact_person']): ?>
                        <div><i class="fas fa-user mr-2 text-blue-600"></i><?php echo htmlspecialchars($district['contact_person']); ?></div>
                    <?php endif; ?>
                    <?php if ($district['phone']): ?>
                        <div><i class="fas fa-phone mr-2 text-green-600"></i><?php echo htmlspecialchars($district['phone']); ?></div>
                    <?php endif; ?>
                    <?php if ($district['email']): ?>
                        <div><i class="fas fa-envelope mr-2 text-orange-600"></i><?php echo htmlspecialchars($district['email']); ?></div>
                    <?php endif; ?>
                </div>
                
                <!-- Stats -->
                <div class="mb-4 p-3 bg-gray-50 rounded-lg text-center">
                    <div class="text-2xl font-bold text-green-600"><?php echo $district['assembly_count']; ?></div>
                    <div class="text-xs text-gray-600">Assemblies</div>
                </div>
                
                <!-- Assigned Admins -->
                <div class="mb-4">
                    <div class="text-sm font-semibold text-gray-700 mb-2">
                        <i class="fas fa-users-cog mr-1"></i>Assigned Admins (<?php echo count($assignedAdmins); ?>)
                    </div>
                    <?php if (count($assignedAdmins) > 0): ?>
                        <div class="space-y-1">
                            <?php foreach ($assignedAdmins as $admin): ?>
                                <div class="flex items-center justify-between text-xs bg-orange-50 p-2 rounded">
                                    <span class="font-medium"><?php echo htmlspecialchars($admin['full_name']); ?></span>
                                    <a href="?remove_assignment=<?php echo $admin['assignment_id']; ?>" 
                                       onclick="return confirm('Remove this admin assignment?')"
                                       class="text-red-600 hover:text-red-800">
                                        <i class="fas fa-times"></i>
                                    </a>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <p class="text-xs text-gray-500 italic">No admins assigned</p>
                    <?php endif; ?>
                </div>
                
                <!-- Actions -->
                <div class="grid grid-cols-3 gap-2 pt-4 border-t border-gray-200">
                    <button onclick='editDistrict(<?php echo json_encode($district); ?>)' 
                            class="btn-gradient text-white px-3 py-2 rounded-lg hover:shadow-lg transition text-sm">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button onclick="assignAdmin(<?php echo $district['id']; ?>, '<?php echo addslashes($district['district_name']); ?>')" 
                            class="bg-green-600 text-white px-3 py-2 rounded-lg hover:bg-green-700 transition text-sm">
                        <i class="fas fa-user-plus"></i>
                    </button>
                    <div class="flex space-x-1">
                        <button onclick="toggleDistrictStatus(<?php echo $district['id']; ?>, <?php echo $district['is_active'] ? '0' : '1'; ?>)" 
                                class="<?php echo $district['is_active'] ? 'bg-yellow-500 hover:bg-yellow-600' : 'bg-blue-600 hover:bg-blue-700'; ?> text-white px-3 py-2 rounded-lg transition text-xs">
                            <i class="fas <?php echo $district['is_active'] ? 'fa-ban' : 'fa-check'; ?> mr-1"></i>
                            <?php echo $district['is_active'] ? 'Deactivate' : 'Activate'; ?>
                        </button>
                        <button onclick="deleteDistrict(<?php echo $district['id']; ?>)" 
                                class="bg-red-600 text-white px-3 py-2 rounded-lg hover:bg-red-700 transition text-sm">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- Add Modal -->
<div id="addModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
    <div class="bg-white rounded-2xl shadow-2xl max-w-2xl w-full max-h-screen overflow-y-auto">
        <div class="p-6 border-b border-gray-200 flex justify-between items-center gradient-bg text-white rounded-t-2xl">
            <h2 class="text-2xl font-bold">Add New District</h2>
            <button onclick="document.getElementById('addModal').classList.add('hidden')" class="text-white hover:text-gray-200">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        
        <form method="POST" class="p-6">
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Select Area *</label>
                    <select name="area_id" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                        <option value="">-- Select Area --</option>
                        <?php foreach ($areas as $area): ?>
                            <option value="<?php echo $area['id']; ?>">
                                <?php echo htmlspecialchars($area['area_name']); ?> (<?php echo $area['area_code']; ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">District Name *</label>
                        <input type="text" name="district_name" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                    </div>
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">District Code *</label>
                        <input type="text" name="district_code" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500" placeholder="e.g., DS001">
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Description</label>
                    <textarea name="description" rows="3" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"></textarea>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Contact Person</label>
                        <input type="text" name="contact_person" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                    </div>
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Phone</label>
                        <input type="tel" name="phone" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Email</label>
                    <input type="email" name="email" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                </div>
                
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Address</label>
                    <textarea name="address" rows="2" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"></textarea>
                </div>
            </div>
            
            <div class="mt-6 flex justify-end space-x-4">
                <button type="button" onclick="document.getElementById('addModal').classList.add('hidden')" 
                        class="px-6 py-2 border border-gray-300 rounded-lg hover:bg-gray-100 transition">
                    Cancel
                </button>
                <button type="submit" name="add_district" 
                        class="btn-gradient text-white px-6 py-2 rounded-lg hover:shadow-lg transition">
                    <i class="fas fa-save mr-2"></i>Save District
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Edit Modal -->
<div id="editModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
    <div class="bg-white rounded-2xl shadow-2xl max-w-2xl w-full max-h-screen overflow-y-auto">
        <div class="p-6 border-b border-gray-200 flex justify-between items-center gradient-bg text-white rounded-t-2xl">
            <h2 class="text-2xl font-bold">Edit District</h2>
            <button onclick="closeEditModal()" class="text-white hover:text-gray-200">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        
        <form method="POST" class="p-6">
            <input type="hidden" name="district_id" id="edit_district_id">
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Select Area *</label>
                    <select name="area_id" id="edit_area_id" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                        <option value="">-- Select Area --</option>
                        <?php foreach ($areas as $area): ?>
                            <option value="<?php echo $area['id']; ?>">
                                <?php echo htmlspecialchars($area['area_name']); ?> (<?php echo $area['area_code']; ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">District Name *</label>
                        <input type="text" name="district_name" id="edit_district_name" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                    </div>
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">District Code *</label>
                        <input type="text" name="district_code" id="edit_district_code" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                    </div>
                </div>
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Description</label>
                    <textarea name="description" id="edit_description" rows="3" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"></textarea>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Contact Person</label>
                        <input type="text" name="contact_person" id="edit_contact" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                    </div>
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Phone</label>
                        <input type="tel" name="phone" id="edit_phone" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                    </div>
                </div>
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Email</label>
                    <input type="email" name="email" id="edit_email" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                </div>
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Address</label>
                    <textarea name="address" id="edit_address" rows="2" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"></textarea>
                </div>
            </div>
            <div class="mt-6 flex justify-end space-x-4">
                <button type="button" onclick="closeEditModal()" class="px-6 py-2 border border-gray-300 rounded-lg hover:bg-gray-100 transition">Cancel</button>
                <button type="submit" name="update_district" class="btn-gradient text-white px-6 py-2 rounded-lg hover:shadow-lg transition">
                    <i class="fas fa-save mr-2"></i>Update District
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Assign Admin Modal -->
<div id="assignModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
    <div class="bg-white rounded-2xl shadow-2xl max-w-md w-full">
        <div class="p-6 border-b border-gray-200 flex justify-between items-center gradient-bg text-white rounded-t-2xl">
            <h2 class="text-2xl font-bold"><i class="fas fa-user-plus mr-2"></i>Assign Admin</h2>
            <button onclick="closeAssignModal()" class="text-white hover:text-gray-200">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        
        <form method="POST" class="p-6">
            <input type="hidden" name="location_id" id="assign_location_id">
            
            <div class="mb-4">
                <p class="text-gray-700 mb-2">Assigning admin to:</p>
                <p class="font-bold text-lg text-gray-800" id="assign_location_name"></p>
            </div>
            
            <div class="mb-4">
                <label class="block text-sm font-semibold text-gray-700 mb-2">Select User *</label>
                <select name="user_id" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                    <option value="">-- Select User --</option>
                    <?php foreach ($users as $user): ?>
                        <option value="<?php echo $user['id']; ?>">
                            <?php echo htmlspecialchars($user['full_name']); ?> 
                            (<?php echo htmlspecialchars($user['email']); ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="flex justify-end space-x-4">
                <button type="button" onclick="closeAssignModal()" class="px-6 py-2 border border-gray-300 rounded-lg hover:bg-gray-100 transition">Cancel</button>
                <button type="submit" name="assign_admin" class="btn-gradient text-white px-6 py-2 rounded-lg hover:shadow-lg transition">
                    <i class="fas fa-check mr-2"></i>Assign
                </button>
            </div>
        </form>
    </div>
</div>
</main>

<script>
function editDistrict(district) {
    document.getElementById('edit_district_id').value = district.id;
    document.getElementById('edit_area_id').value = district.area_id;
    document.getElementById('edit_district_name').value = district.district_name;
    document.getElementById('edit_district_code').value = district.district_code;
    document.getElementById('edit_description').value = district.description || '';
    document.getElementById('edit_contact').value = district.contact_person || '';
    document.getElementById('edit_phone').value = district.phone || '';
    document.getElementById('edit_email').value = district.email || '';
    document.getElementById('edit_address').value = district.address || '';
    document.getElementById('editModal').classList.remove('hidden');
}

function closeEditModal() {
    document.getElementById('editModal').classList.add('hidden');
}

function deleteDistrict(id) {
    if (confirm('Are you sure you want to delete this district? This will also delete all associated assemblies.')) {
        window.location.href = 'districts.php?delete=' + id;
    }
}

function toggleDistrictStatus(id, targetStatus) {
    var msg = targetStatus === 0
        ? 'Deactivate this district and ALL its assemblies and members?'
        : 'Activate this district?';
    if (confirm(msg)) {
        window.location.href = 'districts.php?toggle_active=' + targetStatus + '&id=' + id;
    }
}

function assignAdmin(id, name) {
    document.getElementById('assign_location_id').value = id;
    document.getElementById('assign_location_name').textContent = name;
    document.getElementById('assignModal').classList.remove('hidden');
}

function closeAssignModal() {
    document.getElementById('assignModal').classList.add('hidden');
}
</script>

<?php include '../../includes/footer.php'; ?>

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