<?php include 'inc/funtions.php';
if (isset($_SESSION['user_type'])) {
    $user_id = $_SESSION['user_id'];
    $business_id = $_SESSION['business_id'];
    $user = getUserId($user_id);
    $pages_allowed = check_page_access();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard</title>
    
    <link rel="stylesheet" href="assets/css/bootstrap.css">
    <link rel="stylesheet" href="assets/vendors/chartjs/Chart.min.css">
    <link rel="stylesheet" href="assets/vendors/simple-datatables/style.css">
    <link rel="stylesheet" href="assets/vendors/perfect-scrollbar/perfect-scrollbar.css">
    <link rel="stylesheet" href="assets/css/app.css">
    <link rel="shortcut icon" href="assets/images/favicon.png" type="image/x-icon">
</head>
<body>
    <div id="app">
        <?php include('inc/header.php'); ?>            
            <div class="main-content container-fluid">
                <div class="mb-4">
                    <h3>User Management</h3>
                    <nav aria-label="breadcrumb" class='breadcrumb-header'>
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                            <li class="breadcrumb-item active" aria-current="page">User Management</li>
                        </ol>
                    </nav>
                </div> 
                <section class="section">
                    <div class="row mb-4">
                        <div class="">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h4 class="card-title">User Management</h4>
                                    <div class="d-flex ">
                                        <button type="button" class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#createUser"><i data-feather="plus"></i> Create New User</button>
                                    </div>
                                </div>
                                <div class="card-body px-0 pb-0">
                                    <div class="table-responsive p-3">
                                        <table class='table table-striped mb-0' id="table1">
                                            <thead>
                                                <tr>
                                                    <th>#</th>
                                                    <th>Name</th>
                                                    <th>Phone</th>
                                                    <th>Email</th>
                                                    <th>Status</th>
                                                    <th>Position</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php 
                                                $count = 1;
                                                if (isset($_SESSION['user_type']) && $_SESSION['user_type'] == 'Admin') {
                                                    // code...
                                                    $sql = Querydb("SELECT users.*, user_log.is_active, user_log.id AS log_id, user_log.role_id,user_log.username as username, user_log.email as user_log_email FROM users INNER JOIN user_log ON users.user_id = user_log.user_id WHERE user_log.role_id != 5 AND users.business_id = $business_id  ORDER BY users.user_id DESC");
                                                } else {
                                                    $sql = Querydb("SELECT users.*, user_log.is_active, user_log.id AS log_id, user_log.role_id,user_log.username as username, user_log.email as user_log_email FROM users INNER JOIN user_log ON users.user_id = user_log.user_id WHERE user_log.role_id NOT IN (5, 1) AND users.business_id = $business_id  ORDER BY users.user_id DESC");
                                                }
                                                    foreach ($sql as $auth) {
                                                 ?>
                                                <tr>
                                                    <td><?php echo $count; ?></td>
                                                    <td><?php echo $auth['first_name']." ".$auth['last_name']." ".$auth['middle_name']; ?></td>
                                                    <td><?php echo $auth['phone_no'] ?></td>
                                                    <td><?php echo $auth['email'] ?></td>
                                                    <td>
                                                        <?php if ($auth['is_active'] == 1): ?>
                                                            <span class="badge bg-light-success text-success">Active</span>
                                                        <?php else: ?>
                                                            <span class="badge bg-light-danger text-danger">Deactivated</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <?php if ($auth['role_id'] == 1) { 
                                                            echo "Admin";
                                                        } elseif ($auth['role_id'] == 2) {
                                                           echo "Manager";
                                                        } elseif ($auth['role_id'] == 4) {
                                                            echo "User/Staff";
                                                        } elseif ($auth['role_id'] == 3) {
                                                           echo "Vandor"; 
                                                        } else {
                                                            echo "Member";
                                                        }
                                                         ?>
                                                    </td>
                                                    <td>
                                                        <div class="btn-group">
                                                            <button type="submit" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#editauthModal<?php echo $auth['user_id']; ?>"><i data-feather="edit"></i> Edit</button>
                                                            <button type="button" class="btn btn-secondary" data-bs-toggle="modal" data-bs-target="#viewauthModal<?php echo $auth['user_id']; ?>"><i data-feather="eye"></i> Preview</button>
                                                            <button type="button" class="btn <?php echo ($auth['is_active'] == 1) ? 'btn-danger' : 'btn-success'; ?> status-toggle-btn" data-id="<?php echo $auth['log_id']; ?>" data-status="<?php echo $auth['is_active']; ?>" data-userid="<?php echo $auth['user_id']; ?>" title="<?php echo ($auth['is_active'] == 1) ? 'Deactivate User' : 'Activate User'; ?>">
                                                            <i data-feather="<?php echo ($auth['is_active'] == 1) ? 'user-x' : 'user-check'; ?>"></i> <?php echo ($auth['is_active'] == 1) ? 'Deactivate' : 'Activate'; ?>
                                                        </button>
                                                            <button type="button" class="btn btn-light" data-bs-toggle="modal" data-bs-target="#userRoleAccessModal<?php echo $auth['user_id']; ?>"><i data-feather="settings"></i> Settings</button>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <div class="modal" id="editauthModal<?php echo $auth['user_id']; ?>">
                                                    <div class="modal-dialog modal-dialog-centered">
                                                        <div class="modal-content">
                                                        <div class="modal-header">
                                                            <h4 class="modal-title">Edit User</h4>
                                                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                        </div>
                                                        <div class="modal-body">
                                                            <form class="row g-3 needs-validation" novalidate>
                                                                <div class="col-12">
                                                                    <div class="mb-3">
                                                                        <div class="mt-2 mb-2 d-flex flex-column">
                                                                            <img id="preview" src="assets/images/avatar/<?php echo $auth['profile_img']; ?>" class="img-thumbnail align-self-center justify-content-center" alt="Profile Image Preview" style="max-width: 150px; height: 150px;">
                                                                            <input type="hidden" id="pre_preview_<?php echo $count; ?>" name="" value="<?php echo $auth['profile_img']; ?>">
                                                                        </div>
                                                                        <label for="userEmail" class="form-label">Profile Image</label>
                                                                        <input type="file" class="form-control" id="yourProfilePic_<?php echo $count; ?>" placeholder="Upload profile image">
                                                                    </div>
                                                                    <div class="row mb-3">
                                                                        <input type="hidden" name="id" id="User_id_<?php echo $count; ?>" value="<?php echo $auth['user_id']; ?>">
                                                                        <div class="col-6">
                                                                            <label for="yourFirstName" class="form-label">First Name</label>
                                                                            <input type="text" name="first_name" class="form-control" id="yourFirstName_<?php echo $count; ?>" value="<?php echo $auth['first_name']; ?>">
                                                                        </div>
                                                                        <div class="col-6">
                                                                            <label for="yourLastName" class="form-label">Last Name</label>
                                                                            <input type="text" name="last_name" class="form-control" id="yourLastName_<?php echo $count; ?>" value="<?php echo $auth['last_name']; ?>">
                                                                        </div>
                                                                        <div class="col-6">
                                                                            <label for="yourMiddlename" class="form-label">Middle Name</label>
                                                                            <input type="text" name="middle_name" class="form-control" id="yourMiddlename_<?php echo $count; ?>" value="<?php echo $auth['middle_name']; ?>">
                                                                        </div>
                                                                        <div class="col-6">
                                                                            <label for="phonenumber" class="form-label">Phone Number</label>
                                                                            <input type="text" name="phone_number" class="form-control" id="phonenumber_<?php echo $count; ?>" value="<?php echo $auth['phone_no']; ?>">
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                <div class="col-12">
                                                                    <label for="yourEmail" class="form-label">Your Email</label>
                                                                    <input type="email" name="email" class="form-control" id="yourEmail_<?php echo $count; ?>" value="<?php echo $auth['email']; ?>">
                                                                </div>
                                                            </form>
                                                        </div>

                                                        <!-- Modal footer -->
                                                        <div class="modal-footer">
                                                            <button type="button" class="btn bt n-danger" data-bs-dismiss="modal">Close</button>
                                                            <button class="btn btn-primary" type="submit" id="editauthModalbtn_<?php echo $count; ?>">Edit Profile</button> 
                                                        </div>

                                                        </div>
                                                    </div>
                                                </div>
                                                <!-- View auth Modal --> 
                                                <div class="modal fade" id="viewauthModal<?php echo $auth['user_id']; ?>" tabindex="-1" aria-hidden="true">
                                                    <div class="modal-dialog modal-dialog-centered">
                                                        <div class="modal-content">
                                                            <div class="modal-header border-0 pb-0">
                                                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                            </div>
                                                            <div class="modal-body pt-0">
                                                                <div class="text-center mb-4">
                                                                    <div class="position-relative d-inline-block">
                                                                        <img src="assets/images/avatar/<?php echo $auth['profile_img']; ?>" 
                                                                             alt="Profile" class="rounded-circle shadow-sm border" 
                                                                             style="width: 120px; height: 120px; object-fit: cover;">
                                                                        
                                                                        <span class="position-absolute bottom-0 end-0 p-2 <?php echo ($auth['is_active'] == 1) ? 'bg-success' : 'bg-warning'; ?> border border-light rounded-circle" 
                                                                              title="<?php echo ($auth['is_active'] == 1) ? 'Active' : 'Pending Activation'; ?>">
                                                                        </span>
                                                                    </div>
                                                                    <h4 class="mt-3 mb-0 fw-bold"><?php echo $auth['first_name'].' '.$auth['last_name']; ?></h4>
                                                                    <p class="text-muted"><?php 
                                                                        $roles = [1 => 'Admin', 2 => 'Manager', 3 => 'Vendor', 4 => 'Staff/User'];
                                                                        echo $roles[$auth['role_id']] ?? 'Unknown Role'; 
                                                                    ?></p>
                                                                </div>

                                                                <div class="list-group list-group-flush border-top border-bottom">
                                                                    <div class="list-group-item d-flex justify-content-between align-items-center py-3">
                                                                        <span class="text-muted"><i class="bi bi-person me-2"></i> Username</span>
                                                                        <span class="fw-bold"><?php echo $auth['username']; ?></span>
                                                                    </div>
                                                                    <div class="list-group-item d-flex justify-content-between align-items-center py-3">
                                                                        <span class="text-muted"><i class="bi bi-envelope me-2"></i> Email</span>
                                                                        <span class="fw-bold"><?php echo $auth['email']; ?></span>
                                                                    </div>
                                                                    <div class="list-group-item d-flex justify-content-between align-items-center py-3">
                                                                        <span class="text-muted"><i class="bi bi-phone me-2"></i> Phone</span>
                                                                        <span class="fw-bold"><?php echo $auth['phone_no']; ?></span>
                                                                    </div>
                                                                    <div class="list-group-item d-flex justify-content-between align-items-center py-3">
                                                                        <span class="text-muted"><i class="bi bi-calendar-check me-2"></i> Status</span>
                                                                        <span class="badge <?php echo ($auth['is_active'] == 1) ? 'bg-light-success text-success' : 'bg-light-warning text-warning'; ?>">
                                                                            <?php echo ($auth['is_active'] == 1) ? 'Verified Account' : 'Invitation Sent'; ?>
                                                                        </span>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <div class="modal-footer border-0">
                                                                <div class="d-flex justify-content-between">
                                                                    <button type="button" class="btn btn-secondary mx-3" data-bs-dismiss="modal">Close</button>
                                                                    <button class="btn btn-sm btn-outline-warning" data-bs-toggle="modal" data-bs-target="#resendModal" onclick="openResendModal('<?php echo $auth['log_id']; ?>', '<?php echo $auth['user_log_email']; ?>')">
                                                                        <i class="bi bi-envelope-exclamation"></i> Resend Invitation
                                                                    </button>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <!-- User Role Access Control -->
                                                <div class="modal fade" id="userRoleAccessModal<?php echo $auth['user_id']; ?>" tabindex="-1" role="dialog" aria-labelledby="userRoleAccessModalLabel" aria-hidden="true">
                                                    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
                                                        <div class="modal-content">
                                                            <div class="modal-header">
                                                                <h5 class="modal-title" id="userRoleAccessModalLabel">User Role Access Control</h5>
                                                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                            </div>
                                                            <div class="modal-body">
                                                                <form id="userRoleAccessForm_<?php echo $count; ?>">
                                                                    <div class="mb-3">
                                                                        <label for="selectUser" class="form-label">Select User</label>
                                                                        <input type="hidden" class="form-select" id="user_id_<?php echo $count; ?>" value="<?php echo $auth['user_id']; ?>">
                                                                    </div>
                                                                    <div id="pagePermissionsContainer" style="max-height: 400px; overflow: auto; border: 1px solid #ddd; padding: 10px;">
                                                                        <?php
                                                                        $access_query = "SELECT page FROM user_page_permissions WHERE user_id = {$auth['user_id']}";
                                                                        $access_result = Querydb($access_query);
                                                                        if ($access_row = mysqli_fetch_assoc($access_result)) {
                                                                            $user_allowed_pages = explode(',', $access_row['page']);
                                                                            $user_allowed_pages = array_map('trim', $user_allowed_pages);
                                                                        } else {
                                                                            $user_allowed_pages = [];
                                                                        }
                                                                        $all_pages_sql = Querydb("SELECT * from pages order by page_name");
                                                                        foreach ($all_pages_sql as $p) {
                                                                            $is_checked = in_array($p['page_url'], $user_allowed_pages);
                                                                            $checkbox_id = "pages_{$count}";
                                                                            ?>
                                                                            <div class="form-check">
                                                                                <input 
                                                                                    class="form-check-input form-check-success" 
                                                                                    type="checkbox" name="pages[]" value="<?php echo htmlspecialchars($p['page_url']); ?>" 
                                                                                    <?php echo $is_checked ? 'checked' : ''; ?> 
                                                                                    id="<?php echo $checkbox_id; ?>"
                                                                                >
                                                                                <label class="form-check-label" for="<?php echo $checkbox_id; ?>">
                                                                                    <?php echo htmlspecialchars($p['page_name']); ?>
                                                                                </label>
                                                                            </div>
                                                                        <?php } ?>
                                                                    </div>
                                                                </form>
                                                            </div>
                                                            <div class="modal-footer">
                                                                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                                                                <button type="button" class="btn btn-secondary" id="ResetUserpass_<?php echo $auth['user_id'] ?>">Reset Password</button>
                                                                <button type="button" class="btn btn-primary" id="saveUserRoleAccessBtn_<?php echo $count; ?>">Save Changes</button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <!-- End of User Role Access Control -->
                                                <?php $count++; } ?>
                                            </tbody>
                                        </table>
                                        <div class="modal fade" id="resendModal" tabindex="-1">
                                          <div class="modal-dialog">
                                            <div class="modal-content">
                                              <div class="modal-header">
                                                <h5 class="modal-title">Resend Invitation</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                              </div>
                                              <div class="modal-body">
                                                <p class="text-muted small">If the email address was incorrect, update it below before resending.</p>
                                                <input type="hidden" id="resend_log_id">
                                                <div class="mb-3">
                                                    <label>Recipient Email</label>
                                                    <input type="email" id="resend_email_input" class="form-control" required>
                                                </div>
                                              </div>
                                              <div class="modal-footer">
                                                <button type="button" class="btn btn-primary" onclick="executeResend()">Update & Resend Now</button>
                                              </div>
                                            </div>
                                          </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </section>

            </div>
<?php  include('inc/footer.php'); 
} else {
    header('Location: pages-error-404.html');
    exit;
}?>


