<?php
session_start();
include 'layouts/dbconn.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in and has admin privileges
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$current_user_id = $_SESSION['user_id'];
$sql_current_user = "SELECT u.*, ur.role_name FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_current = $conn->prepare($sql_current_user);
$stmt_current->bind_param("i", $current_user_id);
$stmt_current->execute();
$current_user = $stmt_current->get_result()->fetch_assoc();

if (!in_array($current_user['role_name'], ['Super Admin', 'Hospital Admin'])) {
    header('Location: index.php');
    exit();
}

// Handle AJAX requests for page assignments
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    switch ($_POST['action']) {
        case 'assign_pages_to_role':
            $role_id = intval($_POST['role_id']);
            $pages = $_POST['pages'] ?? [];
            
            try {
                // Start transaction
                $conn->begin_transaction();
                
                // Delete existing page assignments for this role
                $delete_sql = "DELETE FROM role_page_permissions WHERE role_id = ?";
                $delete_stmt = $conn->prepare($delete_sql);
                $delete_stmt->bind_param("i", $role_id);
                $delete_stmt->execute();
                
                // Insert new page assignments
                if (!empty($pages)) {
                    $insert_sql = "INSERT INTO role_page_permissions (role_id, page_name, permission_type, assigned_by, assigned_at) VALUES (?, ?, 'FULL', ?, NOW())";
                    $insert_stmt = $conn->prepare($insert_sql);
                    
                    foreach ($pages as $page) {
                        $insert_stmt->bind_param("isi", $role_id, $page, $current_user_id);
                        $insert_stmt->execute();
                    }
                }
                
                // Log the activity
                $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, new_values, ip_address, user_agent) 
                           VALUES (?, 'PAGE_ASSIGNMENT', 'USER_MANAGEMENT', ?, 'ROLE', ?, ?, ?)";
                $log_stmt = $conn->prepare($log_sql);
                $new_values = json_encode(['pages_assigned' => $pages, 'assigned_by' => $current_user_id]);
                $ip_address = $_SERVER['REMOTE_ADDR'];
                $user_agent = $_SERVER['HTTP_USER_AGENT'];
                $log_stmt->bind_param("iisss", $current_user_id, $role_id, $new_values, $ip_address, $user_agent);
                $log_stmt->execute();
                
                $conn->commit();
                echo json_encode(['success' => true, 'message' => 'Pages assigned to role successfully']);
                
            } catch (Exception $e) {
                $conn->rollback();
                echo json_encode(['success' => false, 'message' => 'Failed to assign pages: ' . $e->getMessage()]);
            }
            exit();
            
        case 'get_role_pages':
            $role_id = intval($_POST['role_id']);
            
            $sql = "SELECT page_name FROM role_page_permissions WHERE role_id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("i", $role_id);
            $stmt->execute();
            $result = $stmt->get_result();
            
            $pages = [];
            while ($row = $result->fetch_assoc()) {
                $pages[] = $row['page_name'];
            }
            
            echo json_encode(['success' => true, 'pages' => $pages]);
            exit();
    }
}

// Create the role_page_permissions table if it doesn't exist
$create_table_sql = "CREATE TABLE IF NOT EXISTS role_page_permissions (
    id INT AUTO_INCREMENT PRIMARY KEY,
    role_id INT NOT NULL,
    page_name VARCHAR(255) NOT NULL,
    permission_type ENUM('FULL', 'READ_ONLY', 'RESTRICTED') DEFAULT 'FULL',
    assigned_by INT NOT NULL,
    assigned_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (role_id) REFERENCES user_roles(role_id),
    FOREIGN KEY (assigned_by) REFERENCES users(user_id),
    UNIQUE KEY unique_role_page (role_id, page_name)
)";
$conn->query($create_table_sql);

// Define all available pages in your system
$available_pages = [
    // Patient Management
    'Patient Management' => [
        'list_patients.php' => 'View All Patients',
        'register_patient.php' => 'Register New Patient',
        'edit_patient.php' => 'Edit Patient Information',
        'patient_search.php' => 'Search Patients',
        'patient_records.php' => 'Patient Medical Records',
        'medical_history.php' => 'Patient Medical History',
        'export_patients.php' => 'Export Patient Data'
    ],
    
    // Patient Visits
    'Patient Visits' => [
        'list_visits.php' => 'View All Visits',
        'register_visit.php' => 'Register Patient Visit',
        'edit_visit.php' => 'Edit Visit Information',
        'visit_queue.php' => 'Visit Queue Management',
        'visit_history.php' => 'Visit History',
        'emergency_visits.php' => 'Emergency Visits'
    ],
    
    // Clinical Operations
    'Clinical Operations' => [
        'list_consultations.php' => 'View All Consultations',
        'conduct_consultation.php' => 'Conduct Consultations',
        'edit_consultation.php' => 'Edit Consultation Records',
        'consultation_queue.php' => 'Consultation Queue',
        'consultation_reports.php' => 'Consultation Reports',
        'active_consultations.php' => 'Active Consultations'
    ],
    
    // Procedures
    'Procedures' => [
        'list_procedures.php' => 'View All Procedures',
        'perform_procedure.php' => 'Perform Procedures',
        'schedule_procedure.php' => 'Schedule Procedures',
        'procedure_types.php' => 'Manage Procedure Types',
        'procedure_history.php' => 'Procedure History',
        'procedure_reports.php' => 'Procedure Reports'
    ],
    
    // Laboratory Management
    'Laboratory' => [
        'list_lab_orders.php' => 'View Lab Orders',
        'create_lab_order.php' => 'Create Lab Orders',
        'pending_lab_orders.php' => 'Pending Lab Orders',
        'process_lab_tests.php' => 'Process Lab Tests',
        'enter_lab_results.php' => 'Enter Lab Results',
        'approve_lab_results.php' => 'Approve Lab Results',
        'lab_results.php' => 'View Lab Results',
        'lab_reports.php' => 'Lab Reports',
        'lab_test_types.php' => 'Lab Test Types'
    ],
    
    // Financial Management
    'Billing & Payments' => [
        'list_invoices.php' => 'View All Invoices',
        'create_invoice.php' => 'Create Invoices',
        'pending_invoices.php' => 'Pending Invoices',
        'overdue_invoices.php' => 'Overdue Invoices',
        'list_payments.php' => 'View All Payments',
        'record_payment.php' => 'Record Payments',
        'mpesa_payments.php' => 'M-Pesa Payments',
        'payment_reports.php' => 'Payment Reports',
        'outstanding_balances.php' => 'Outstanding Balances'
    ],
    
    // Revenue & Credit
    'Revenue & Financial' => [
        'daily_revenue.php' => 'Daily Revenue Reports',
        'monthly_revenue.php' => 'Monthly Revenue Reports',
        'revenue_analysis.php' => 'Revenue Analysis',
        'financial_reports.php' => 'Financial Reports',
        'facility_credit_score.php' => 'Facility Credit Score',
        'credit_history.php' => 'Credit History',
        'facility_loan_applications.php' => 'Loan Applications',
        'active_facility_loans.php' => 'Active Loans',
        'commission_calculations.php' => 'Commission Management'
    ],
    
    // User Management
    'User Management' => [
        'list_users.php' => 'View All Users',
        'add_user.php' => 'Add New Users',
        'edit_user.php' => 'Edit User Information',
        'user_roles.php' => 'Manage User Roles',
        'role_permissions.php' => 'Role Permissions',
        'access_control.php' => 'Access Control & Role Assignment',
        'staff_performance.php' => 'Staff Performance Reports'
    ],
    
    // Reports & Analytics
    'Reports & Analytics' => [
        'patient_statistics.php' => 'Patient Statistics',
        'doctor_performance_report.php' => 'Doctor Performance',
        'department_performance.php' => 'Department Performance',
        'service_utilization.php' => 'Service Utilization',
        'lab_statistics.php' => 'Laboratory Statistics',
        'clinical_reports.php' => 'Clinical Reports',
        'custom_reports.php' => 'Custom Reports'
    ],
    
    // Communications
    'Communications' => [
        'sms_management.php' => 'SMS Management',
        'email_management.php' => 'Email Management',
        'bulk_messaging.php' => 'Bulk Messaging',
        'communication_templates.php' => 'Communication Templates',
        'appointment_reminders.php' => 'Appointment Reminders'
    ],
    
    // System Administration
    'System Administration' => [
        'system_settings.php' => 'System Configuration',
        'mpesa_config.php' => 'M-Pesa Configuration',
        'email_config.php' => 'Email Configuration',
        'backup_restore.php' => 'Backup & Restore',
        'activity_logs.php' => 'Activity Logs',
        'security_logs.php' => 'Security Logs',
        'branch_management.php' => 'Branch Management'
    ]
];

// Get all roles
$roles_sql = "SELECT role_id, role_name, description FROM user_roles WHERE is_active = 1 ORDER BY role_name";
$roles_result = $conn->query($roles_sql);

// Get current page assignments for all roles
$page_assignments_sql = "SELECT rpp.role_id, rpp.page_name, ur.role_name 
                        FROM role_page_permissions rpp 
                        INNER JOIN user_roles ur ON rpp.role_id = ur.role_id 
                        WHERE ur.is_active = 1
                        ORDER BY ur.role_name, rpp.page_name";
$page_assignments = $conn->query($page_assignments_sql);

// Organize assignments by role
$role_page_assignments = [];
while ($assignment = $page_assignments->fetch_assoc()) {
    $role_page_assignments[$assignment['role_id']][] = $assignment['page_name'];
}
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Page & Role Assignment - Healthcare EMR System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- SweetAlert CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        .page-header {
            background: linear-gradient(135deg, #7c3aed 0%, #8b5cf6 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .page-title {
            font-size: 1.75rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .page-subtitle {
            opacity: 0.9;
            margin: 0;
        }
        
        .card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .card-header {
            background: #f8fafc;
            border-bottom: 1px solid #e2e8f0;
            border-radius: 12px 12px 0 0;
            padding: 1.25rem;
        }
        
        .card-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .role-selector {
            margin-bottom: 2rem;
        }
        
        .role-card {
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .role-card:hover {
            border-color: #8b5cf6;
            box-shadow: 0 4px 12px rgba(139, 92, 246, 0.15);
        }
        
        .role-card.active {
            border-color: #7c3aed;
            background: #f3f4f6;
            box-shadow: 0 4px 12px rgba(124, 58, 237, 0.2);
        }
        
        .role-name {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .role-description {
            color: #64748b;
            font-size: 0.875rem;
        }
        
        .page-section {
            margin-bottom: 2rem;
        }
        
        .section-title {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1rem;
            padding: 0.75rem;
            background: #f1f5f9;
            border-radius: 6px;
            border-left: 4px solid #8b5cf6;
        }
        
        .page-checkbox {
            display: flex;
            align-items: center;
            padding: 0.75rem;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            margin-bottom: 0.5rem;
            transition: all 0.2s ease;
        }
        
        .page-checkbox:hover {
            background: #f8fafc;
            border-color: #8b5cf6;
        }
        
        .page-checkbox input[type="checkbox"] {
            margin-right: 0.75rem;
            transform: scale(1.2);
        }
        
        .page-checkbox label {
            margin: 0;
            font-weight: 500;
            color: #374151;
            cursor: pointer;
            flex: 1;
        }
        
        .page-file {
            font-size: 0.75rem;
            color: #6b7280;
            font-family: monospace;
            background: #f3f4f6;
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
        }
        
        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.875rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
            text-decoration: none;
            display: inline-block;
        }
        
        .btn-primary {
            background: #7c3aed;
            color: white;
        }
        
        .btn-primary:hover {
            background: #6d28d9;
            color: white;
        }
        
        .btn-success {
            background: #059669;
            color: white;
        }
        
        .btn-success:hover {
            background: #047857;
            color: white;
        }
        
        .btn-secondary {
            background: #6b7280;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #4b5563;
            color: white;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 8px;
            padding: 1.5rem;
            border: 1px solid #e2e8f0;
            text-align: center;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            margin-top: 0.5rem;
        }
        
        .alert-info {
            background: #dbeafe;
            border: 1px solid #3b82f6;
            color: #1e40af;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 2rem;
        }
        
        .loading {
            opacity: 0.6;
            pointer-events: none;
        }
        
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="page-header">
                        <h1 class="page-title">
                            <i class="ph-shield-check me-2"></i>Page & Role Assignment
                        </h1>
                        <p class="page-subtitle">Assign specific pages and features to user roles</p>
                    </div>

                    <!-- Instructions -->
                    <div class="alert-info">
                        <h6 style="margin: 0 0 0.5rem 0;">
                            <i class="ph-info me-2"></i>How Page Assignment Works
                        </h6>
                        <p style="margin: 0; font-size: 0.875rem;">
                            1. Select a role from the list below<br>
                            2. Check the pages/features you want that role to access<br>
                            3. Click "Assign Pages to Role" to save<br>
                            4. Users with that role will only see the assigned pages in their menu
                        </p>
                    </div>

                    <!-- Statistics -->
                    <div class="stats-grid">
                        <?php
                        $total_pages = 0;
                        foreach ($available_pages as $pages) {
                            $total_pages += count($pages);
                        }
                        
                        $roles_result->data_seek(0);
                        $total_roles = $roles_result->num_rows;
                        ?>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $total_pages; ?></div>
                            <div class="stat-label">Available Pages</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $total_roles; ?></div>
                            <div class="stat-label">User Roles</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo count($role_page_assignments); ?></div>
                            <div class="stat-label">Roles with Assignments</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo array_sum(array_map('count', $role_page_assignments)); ?></div>
                            <div class="stat-label">Total Assignments</div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Role Selection -->
                        <div class="col-lg-4">
                            <div class="card">
                                <div class="card-header">
                                    <h3 class="card-title">
                                        <i class="ph-users me-2"></i>Select Role
                                    </h3>
                                </div>
                                <div class="card-body">
                                    <div class="role-selector">
                                        <?php 
                                        $roles_result->data_seek(0);
                                        while ($role = $roles_result->fetch_assoc()): 
                                        ?>
                                        <div class="role-card" onclick="selectRole(<?php echo $role['role_id']; ?>, '<?php echo htmlspecialchars($role['role_name']); ?>')" 
                                             id="role-<?php echo $role['role_id']; ?>">
                                            <div class="role-name"><?php echo htmlspecialchars($role['role_name']); ?></div>
                                            <div class="role-description">
                                                <?php echo htmlspecialchars($role['description'] ?? 'No description'); ?>
                                            </div>
                                            <div style="margin-top: 0.5rem; font-size: 0.75rem; color: #059669;">
                                                <?php 
                                                $assigned_count = count($role_page_assignments[$role['role_id']] ?? []);
                                                echo $assigned_count . ' pages assigned';
                                                ?>
                                            </div>
                                        </div>
                                        <?php endwhile; ?>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Page Assignment -->
                        <div class="col-lg-8">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h3 class="card-title">
                                        <i class="ph-files me-2"></i>Assign Pages to Role
                                    </h3>
                                    <div>
                                        <button class="btn btn-secondary me-2" onclick="selectAllPages()">
                                            <i class="ph-check-square me-1"></i>Select All
                                        </button>
                                        <button class="btn btn-secondary me-2" onclick="clearAllPages()">
                                            <i class="ph-square me-1"></i>Clear All
                                        </button>
                                        <button class="btn btn-success" onclick="assignPagesToRole()" id="assignBtn" disabled>
                                            <i class="ph-floppy-disk me-1"></i>Assign Pages to Role
                                        </button>
                                    </div>
                                </div>
                                <div class="card-body" id="pageAssignmentArea">
                                    <div class="text-center p-5" style="color: #64748b;">
                                        <i class="ph-hand-pointing display-1 mb-3"></i>
                                        <h5>Select a role to assign pages</h5>
                                        <p>Choose a user role from the left panel to start assigning pages and features.</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        let selectedRoleId = null;
        let selectedRoleName = null;
        
        const availablePages = <?php echo json_encode($available_pages); ?>;
        
        function selectRole(roleId, roleName) {
            selectedRoleId = roleId;
            selectedRoleName = roleName;
            
            // Update UI
            $('.role-card').removeClass('active');
            $(`#role-${roleId}`).addClass('active');
            
            // Enable assign button
            $('#assignBtn').prop('disabled', false);
            
            // Load pages for this role
            loadRolePages(roleId, roleName);
        }
        
        function loadRolePages(roleId, roleName) {
            $('#pageAssignmentArea').addClass('loading');
            
            $.ajax({
                url: '',
                method: 'POST',
                data: {
                    action: 'get_role_pages',
                    role_id: roleId
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        renderPageAssignment(roleName, response.pages);
                    } else {
                        Swal.fire('Error', 'Failed to load role pages', 'error');
                    }
                },
                error: function() {
                    Swal.fire('Error', 'Failed to load role pages', 'error');
                },
                complete: function() {
                    $('#pageAssignmentArea').removeClass('loading');
                }
            });
        }
        
        function renderPageAssignment(roleName, assignedPages) {
            let html = `
                <div class="mb-4">
                    <h5 style="color: #7c3aed;">Assigning pages to: <strong>${roleName}</strong></h5>
                    <p style="color: #64748b; font-size: 0.875rem;">Select the pages this role should have access to:</p>
                </div>
            `;
            
            Object.keys(availablePages).forEach(section => {
                html += `
                    <div class="page-section">
                        <div class="section-title">
                            <i class="ph-folder me-2"></i>${section}
                        </div>
                `;
                
                Object.keys(availablePages[section]).forEach(page => {
                    const isChecked = assignedPages.includes(page) ? 'checked' : '';
                    html += `
                        <div class="page-checkbox">
                            <input type="checkbox" id="page-${page}" name="pages[]" value="${page}" ${isChecked}>
                            <label for="page-${page}">${availablePages[section][page]}</label>
                            <span class="page-file">${page}</span>
                        </div>
                    `;
                });
                
                html += '</div>';
            });
            
            $('#pageAssignmentArea').html(html);
        }
        
        function selectAllPages() {
            $('#pageAssignmentArea input[type="checkbox"]').prop('checked', true);
        }
        
        function clearAllPages() {
            $('#pageAssignmentArea input[type="checkbox"]').prop('checked', false);
        }
        
        function assignPagesToRole() {
            if (!selectedRoleId) {
                Swal.fire('Error', 'Please select a role first', 'error');
                return;
            }
            
            const selectedPages = [];
            $('#pageAssignmentArea input[type="checkbox"]:checked').each(function() {
                selectedPages.push($(this).val());
            });
            
            Swal.fire({
                title: 'Confirm Assignment',
                text: `Assign ${selectedPages.length} pages to ${selectedRoleName}?`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Yes, Assign Pages',
                confirmButtonColor: '#7c3aed',
                cancelButtonColor: '#6b7280'
            }).then((result) => {
                if (result.isConfirmed) {
                    performPageAssignment(selectedPages);
                }
            });
        }
        
        function performPageAssignment(pages) {
            $('#assignBtn').prop('disabled', true).html('<i class="ph-spinner me-1"></i>Assigning...');
            
            $.ajax({
                url: '',
                method: 'POST',
                data: {
                    action: 'assign_pages_to_role',
                    role_id: selectedRoleId,
                    pages: pages
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success!',
                            text: response.message,
                            timer: 2000,
                            showConfirmButton: false
                        }).then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire('Error', response.message, 'error');
                    }
                },
                error: function() {
                    Swal.fire('Error', 'Failed to assign pages. Please try again.', 'error');
                },
                complete: function() {
                    $('#assignBtn').prop('disabled', false).html('<i class="ph-floppy-disk me-1"></i>Assign Pages to Role');
                }
            });
        }
        
        $(document).ready(function() {
            console.log('Page Assignment system loaded');
        });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>

<?php $conn->close(); ?>