<?php
define('ROVO_APP', true);
require_once '../config.php';
require_once '../Auth.php';

$page_title = 'Admin Management';

if (!$auth->hasPermission('can_manage_users') && !$auth->hasRole('super_admin')) {
    $_SESSION['error'] = "You don't have permission to access this page";
    header('Location: dashboard.php');
    exit;
}

$current_user = $auth->getCurrentUser();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_admin'])) {
    $data = [
        'first_name' => $_POST['first_name'] ?? '',
        'last_name' => $_POST['last_name'] ?? '',
        'email' => $_POST['email'] ?? '',
        'phone' => $_POST['phone'] ?? '',
        'password' => $_POST['password'] ?? '',
        'role' => $_POST['role'] ?? 'junior_admin'
    ];
    
    if ($auth->createAdmin($data, $current_user['id'])) {
        $_SESSION['success'] = "Admin created successfully";
        header('Location: admins.php');
        exit;
    } else {
        $errors = $auth->getErrors();
    }
}

// Handle AJAX actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    $action = $_POST['action'];
    $admin_id = (int)($_POST['admin_id'] ?? 0);
    
    if ($action === 'update_permissions' && $auth->hasRole('super_admin')) {
        $permissions = [
            'can_create' => isset($_POST['can_create']) ? 1 : 0,
            'can_edit' => isset($_POST['can_edit']) ? 1 : 0,
            'can_delete' => isset($_POST['can_delete']) ? 1 : 0,
            'can_view' => 1,
            'can_manage_users' => isset($_POST['can_manage_users']) ? 1 : 0,
            'can_manage_payments' => isset($_POST['can_manage_payments']) ? 1 : 0,
            'can_manage_properties' => isset($_POST['can_manage_properties']) ? 1 : 0,
            'can_verify_documents' => isset($_POST['can_verify_documents']) ? 1 : 0
        ];
        
        $sql = "UPDATE admin_permissions SET 
                can_create = ?, can_edit = ?, can_delete = ?,
                can_manage_users = ?, can_manage_payments = ?,
                can_manage_properties = ?, can_verify_documents = ?
                WHERE admin_id = ?";
        
        $db->execute($sql, [
            $permissions['can_create'], $permissions['can_edit'], $permissions['can_delete'],
            $permissions['can_manage_users'], $permissions['can_manage_payments'],
            $permissions['can_manage_properties'], $permissions['can_verify_documents'],
            $admin_id
        ]);
        
        echo json_encode(['success' => true, 'message' => 'Permissions updated']);
        exit;
    }
    
    if ($action === 'suspend' && $auth->hasRole('super_admin')) {
        $auth->suspendUser($admin_id, $current_user['id']);
        echo json_encode(['success' => true, 'message' => 'Admin suspended']);
        exit;
    }
    
    if ($action === 'activate' && $auth->hasRole('super_admin')) {
        $auth->activateUser($admin_id, $current_user['id']);
        echo json_encode(['success' => true, 'message' => 'Admin activated']);
        exit;
    }
}

// Get all admins
$sql = "SELECT u.*, ap.*,
        CONCAT(creator.first_name, ' ', creator.last_name) as created_by_name
        FROM users u
        LEFT JOIN admin_permissions ap ON u.id = ap.admin_id
        LEFT JOIN users creator ON u.created_by = creator.id
        WHERE u.role IN ('admin', 'junior_admin')
        ORDER BY u.created_at DESC";

$admins = $db->fetchAll($sql);

// Get super admins separately
$super_admins = $db->fetchAll("SELECT * FROM users WHERE role = 'super_admin' ORDER BY created_at");

include 'includes/header.php';
?>

<style>
    .permission-badge {
        padding: 5px 10px;
        border-radius: 5px;
        font-size: 0.85rem;
        display: inline-block;
        margin: 2px;
    }
    .permission-badge.active {
        background: rgba(40, 167, 69, 0.1);
        color: #28a745;
    }
    .permission-badge.inactive {
        background: rgba(108, 117, 125, 0.1);
        color: #6c757d;
    }
</style>

<div class="page-header">
    <h1>Admin Management</h1>
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
            <li class="breadcrumb-item active">Admin Management</li>
        </ol>
    </nav>
</div>

<?php if (isset($_SESSION['success'])): ?>
<div class="alert alert-success alert-dismissible fade show">
    <i class="fas fa-check-circle"></i> <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<?php if (isset($errors) && !empty($errors)): ?>
<div class="alert alert-danger alert-dismissible fade show">
    <ul class="mb-0">
        <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
        <?php endforeach; ?>
    </ul>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- Super Admins -->
<div class="card mb-4">
    <div class="card-header" style="background: linear-gradient(135deg, #D4A017 0%, #B8974A 100%);">
        <h5 class="mb-0 text-white"><i class="fas fa-crown"></i> Super Administrators</h5>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Admin</th>
                        <th>Email</th>
                        <th>Phone</th>
                        <th>Status</th>
                        <th>Last Login</th>
                        <th>Registered</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($super_admins as $admin): ?>
                    <tr>
                        <td>
                            <div class="d-flex align-items-center">
                                <div class="user-avatar me-3" style="width: 45px; height: 45px; font-size: 1rem;">
                                    <?php echo strtoupper(substr($admin['first_name'], 0, 1) . substr($admin['last_name'], 0, 1)); ?>
                                </div>
                                <div>
                                    <strong><?php echo htmlspecialchars($admin['first_name'] . ' ' . $admin['last_name']); ?></strong>
                                    <br>
                                    <span class="badge" style="background: #D4A017;">Super Admin</span>
                                </div>
                            </div>
                        </td>
                        <td><?php echo htmlspecialchars($admin['email']); ?></td>
                        <td><?php echo htmlspecialchars($admin['phone']); ?></td>
                        <td><span class="badge bg-success">Active</span></td>
                        <td>
                            <?php echo $admin['last_login'] ? date('M d, Y H:i', strtotime($admin['last_login'])) : 'Never'; ?>
                        </td>
                        <td><?php echo date('M d, Y', strtotime($admin['created_at'])); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Regular Admins -->
<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="fas fa-user-shield"></i> Admin Users</h5>
        <?php if ($auth->hasPermission('can_manage_users') || $auth->hasRole('super_admin')): ?>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createAdminModal">
            <i class="fas fa-plus"></i> Create New Admin
        </button>
        <?php endif; ?>
    </div>
    
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Admin</th>
                        <th>Contact</th>
                        <th>Role</th>
                        <th>Permissions</th>
                        <th>Status</th>
                        <th>Created By</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($admins)): ?>
                    <tr>
                        <td colspan="7" class="text-center py-4">
                            <i class="fas fa-user-shield fa-3x text-muted mb-3 d-block"></i>
                            <p class="text-muted">No admin users found</p>
                        </td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($admins as $admin): ?>
                        <tr>
                            <td>
                                <div class="d-flex align-items-center">
                                    <div class="user-avatar me-3" style="width: 45px; height: 45px; font-size: 1rem;">
                                        <?php echo strtoupper(substr($admin['first_name'], 0, 1) . substr($admin['last_name'], 0, 1)); ?>
                                    </div>
                                    <div>
                                        <strong><?php echo htmlspecialchars($admin['first_name'] . ' ' . $admin['last_name']); ?></strong>
                                        <br>
                                        <small class="text-muted">ID: <?php echo $admin['id']; ?></small>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <i class="fas fa-envelope"></i> <?php echo htmlspecialchars($admin['email']); ?>
                                <br>
                                <i class="fas fa-phone"></i> <?php echo htmlspecialchars($admin['phone']); ?>
                            </td>
                            <td>
                                <?php
                                $role_badge = $admin['role'] === 'admin' ? 'primary' : 'info';
                                ?>
                                <span class="badge bg-<?php echo $role_badge; ?>">
                                    <?php echo ucfirst(str_replace('_', ' ', $admin['role'])); ?>
                                </span>
                            </td>
                            <td>
                                <div>
                                    <?php if ($admin['can_create']): ?>
                                    <span class="permission-badge active">Create</span>
                                    <?php endif; ?>
                                    
                                    <?php if ($admin['can_edit']): ?>
                                    <span class="permission-badge active">Edit</span>
                                    <?php endif; ?>
                                    
                                    <?php if ($admin['can_delete']): ?>
                                    <span class="permission-badge active">Delete</span>
                                    <?php endif; ?>
                                    
                                    <?php if (!$admin['can_create'] && !$admin['can_edit'] && !$admin['can_delete']): ?>
                                    <span class="permission-badge inactive">View Only</span>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td>
                                <?php
                                $status_badge = [
                                    'active' => 'success',
                                    'suspended' => 'danger',
                                    'pending' => 'warning'
                                ][$admin['status']] ?? 'secondary';
                                ?>
                                <span class="badge bg-<?php echo $status_badge; ?>">
                                    <?php echo ucfirst($admin['status']); ?>
                                </span>
                            </td>
                            <td>
                                <?php echo htmlspecialchars($admin['created_by_name'] ?? 'System'); ?>
                                <br>
                                <small class="text-muted"><?php echo date('M d, Y', strtotime($admin['created_at'])); ?></small>
                            </td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <?php if ($auth->hasRole('super_admin')): ?>
                                    <button type="button" class="btn btn-outline-primary edit-permissions" 
                                            data-id="<?php echo $admin['id']; ?>"
                                            data-bs-toggle="tooltip" title="Edit Permissions">
                                        <i class="fas fa-key"></i>
                                    </button>
                                    
                                    <?php if ($admin['status'] === 'active'): ?>
                                    <button type="button" class="btn btn-outline-warning suspend-admin" 
                                            data-id="<?php echo $admin['id']; ?>"
                                            data-name="<?php echo htmlspecialchars($admin['first_name'] . ' ' . $admin['last_name']); ?>"
                                            data-bs-toggle="tooltip" title="Suspend">
                                        <i class="fas fa-ban"></i>
                                    </button>
                                    <?php else: ?>
                                    <button type="button" class="btn btn-outline-success activate-admin" 
                                            data-id="<?php echo $admin['id']; ?>"
                                            data-name="<?php echo htmlspecialchars($admin['first_name'] . ' ' . $admin['last_name']); ?>"
                                            data-bs-toggle="tooltip" title="Activate">
                                        <i class="fas fa-check"></i>
                                    </button>
                                    <?php endif; ?>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Create Admin Modal -->
<div class="modal fade" id="createAdminModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Create New Admin</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" data-validate="true">
                <div class="modal-body">
                    <input type="hidden" name="csrf_token" value="<?php echo Security::generateCSRFToken(); ?>">
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">First Name <span class="text-danger">*</span></label>
                            <input type="text" name="first_name" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Last Name <span class="text-danger">*</span></label>
                            <input type="text" name="last_name" class="form-control" required>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Email <span class="text-danger">*</span></label>
                            <input type="email" name="email" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Phone <span class="text-danger">*</span></label>
                            <input type="tel" name="phone" class="form-control" required 
                                   pattern="^(\+?234|0)[789]\d{9}$">
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Role <span class="text-danger">*</span></label>
                            <select name="role" class="form-select" required>
                                <option value="junior_admin">Junior Admin (View Only)</option>
                                <option value="admin">Admin (Create & Edit)</option>
                            </select>
                            <small class="text-muted">Junior admins can only view. Admins can create and edit but not delete.</small>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Password <span class="text-danger">*</span></label>
                            <input type="password" name="password" class="form-control" required minlength="8">
                            <small class="text-muted">Minimum 8 characters</small>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="create_admin" class="btn btn-primary">
                        <i class="fas fa-user-plus"></i> Create Admin
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Permissions Modal -->
<div class="modal fade" id="permissionsModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Permissions</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="permissionsForm">
                    <input type="hidden" id="permAdminId" name="admin_id">
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="can_create" id="perm_create">
                            <label class="form-check-label" for="perm_create">
                                <strong>Can Create</strong> - Add new properties, lands, materials
                            </label>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="can_edit" id="perm_edit">
                            <label class="form-check-label" for="perm_edit">
                                <strong>Can Edit</strong> - Modify existing records
                            </label>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="can_delete" id="perm_delete">
                            <label class="form-check-label" for="perm_delete">
                                <strong>Can Delete</strong> - Remove records
                            </label>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="can_manage_users" id="perm_users">
                            <label class="form-check-label" for="perm_users">
                                <strong>Manage Users</strong> - User management access
                            </label>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="can_manage_payments" id="perm_payments">
                            <label class="form-check-label" for="perm_payments">
                                <strong>Manage Payments</strong> - Payment tracking access
                            </label>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="can_manage_properties" id="perm_properties">
                            <label class="form-check-label" for="perm_properties">
                                <strong>Manage Properties</strong> - Property management access
                            </label>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="can_verify_documents" id="perm_verify">
                            <label class="form-check-label" for="perm_verify">
                                <strong>Verify Documents</strong> - Document verification access
                            </label>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="savePermissions">
                    <i class="fas fa-save"></i> Save Permissions
                </button>
            </div>
        </div>
    </div>
</div>

<script>
    
    $(document).ready(function() {
        // Edit permissions
        $('.edit-permissions').click(function() {
            const adminId = $(this).data('id');
            
            $.get('ajax/get-admin-permissions.php', { id: adminId }, function(data) {
                $('#permAdminId').val(adminId);
                $('#perm_create').prop('checked', data.can_create == 1);
                $('#perm_edit').prop('checked', data.can_edit == 1);
                $('#perm_delete').prop('checked', data.can_delete == 1);
                $('#perm_users').prop('checked', data.can_manage_users == 1);
                $('#perm_payments').prop('checked', data.can_manage_payments == 1);
                $('#perm_properties').prop('checked', data.can_manage_properties == 1);
                $('#perm_verify').prop('checked', data.can_verify_documents == 1);
                
                $('#permissionsModal').modal('show');
            }, 'json');
        });
        
        // Save permissions
        $('#savePermissions').click(function() {
            const formData = $('#permissionsForm').serialize() + 
                '&action=update_permissions&csrf_token=<?php echo Security::generateCSRFToken(); ?>';
            
            $.post('admins.php', formData, function(response) {
                if (response.success) {
                    $('#permissionsModal').modal('hide');
                    Swal.fire('Success', response.message, 'success')
                        .then(() => location.reload());
                } else {
                    Swal.fire('Error', response.message, 'error');
                }
            }, 'json');
        });
        
        // Suspend admin
        $('.suspend-admin').click(function() {
            const adminId = $(this).data('id');
            const adminName = $(this).data('name');
            
            Swal.fire({
                title: 'Suspend Admin?',
                html: `Suspend <strong>${adminName}</strong>?`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#ffc107',
                confirmButtonText: 'Yes, suspend'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.post('admins.php', {
                        action: 'suspend',
                        admin_id: adminId,
                        csrf_token: '<?php echo Security::generateCSRFToken(); ?>'
                    }, function(response) {
                        if (response.success) {
                            Swal.fire('Suspended!', response.message, 'success')
                                .then(() => location.reload());
                        }
                    }, 'json');
                }
            });
        });
        
        // Activate admin
        $('.activate-admin').click(function() {
            const adminId = $(this).data('id');
            const adminName = $(this).data('name');
            
            Swal.fire({
                title: 'Activate Admin?',
                html: `Activate <strong>${adminName}</strong>?`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#28a745',
                confirmButtonText: 'Yes, activate'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.post('admins.php', {
                        action: 'activate',
                        admin_id: adminId,
                        csrf_token: '<?php echo Security::generateCSRFToken(); ?>'
                    }, function(response) {
                        if (response.success) {
                            Swal.fire('Activated!', response.message, 'success')
                                .then(() => location.reload());
                        }
                    }, 'json');
                }
            });
        });
        
        $('[data-bs-toggle="tooltip"]').tooltip();
    });
</script>

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