<?php 
session_start();

if (!isset($_SESSION['login'])) {
    header('location:login.php');
    exit;
}

if (isset($_SESSION['role']))
{
    if ($_SESSION['role'] == "user" || $_SESSION['role'] == "member")
   {
    header('location:dashboard.php');
    exit;
   }
}

require 'function.php';
require 'config.php';

// Menampilkan semua data dari table users_id berdasarkan nama secara Descending
$users_id = query("SELECT * FROM users_id ORDER BY id DESC");
$result = mysqli_query($koneksi, "SELECT * FROM users_id  WHERE id='1'");
$whatsapp = mysqli_fetch_assoc($result);
$pesan = $whatsapp['whatsapp'];
$user_role = $whatsapp['role'];
$hasil = mysqli_query($koneksi, "SELECT * FROM users_id" );
$check = mysqli_fetch_assoc($hasil);
$apikey = $check['apikey'];

if (isset($_POST['simpan'])) {
    $result = add_user($_POST);
    if ($result) {
        // redirect( "/user.php" );
        echo "<script>
                // alert('User berhasil ditambahkan!');
                window.location.href='user.php';
            </script>";
    } else {
        echo "<script>
                alert('User gagal ditambahkan!');
            </script>";
    }
}

require 'header.php';
?>
<body>

    <!-- Container -->
    <div class="container py-4">
        
        <div class="row mb-4">
            <div class="col-md-12">
                 <h3 class="fw-bold text-gradient d-inline-block">User Management</h3>
                 <p class="text-muted">Manage system administrators and users.</p>
            </div>
        </div>

        <div class="glass-card">
            <div class="d-flex justify-content-between mb-3">
                 <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#AddData">
                    <i class="bi bi-person-plus-fill"></i> Add New User
                 </button>
            </div>
            
            <div class="table-responsive">
                <table id="data" class="table table-hover align-middle mb-0" style="width:100%;">
                    <thead>
                        <tr>
                            <th class="text-center">No.</th>
                            <th>Username</th>
                            <th>Email</th>
                            <th>Phone</th>
                            <th>Role</th>
                            <th>Expiry</th>
                            <th>Join Date</th>
                            <th class="text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $no=1; ?>
                        <?php foreach ($users_id as $row) : ?>
                            <tr>
                                <td class="text-center" data-label="No."><?= $no++; ?></td>
                                <td class="fw-bold" data-label="Username"><?= $row['username']; ?></td>
                                <td data-label="Email"><?= $row['email']; ?></td>
                                <td data-label="Phone"><?= $row['phone']; ?></td>
                                <td data-label="Role"><span class="badge bg-secondary rounded-pill"><?= $row['role']; ?></span></td>
                                <td data-label="Expiry">
                                    <?php if ($row['role'] == 'admin'): ?>
                                        <span class="text-muted">-</span>
                                    <?php else: ?>
                                        <?php if ($row['subscription_period'] == 'Tidak Aktif'): ?>
                                            <span class="badge bg-danger">Inactive</span>
                                        <?php else: ?>
                                            <?= $row['expiry_date'] ? date('d-m-Y', strtotime($row['expiry_date'])) : '-'; ?>
                                            <?php if ($row['expiry_date'] && strtotime($row['expiry_date']) < time()): ?>
                                                <br><span class="badge bg-danger small">Expired</span>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </td>
                                <td data-label="Join Date"><?= $row['register_date']; ?></td>
                                <td class="text-center" data-label="Actions">
                                    <div class="d-flex gap-1 justify-content-center">
                                         <button type="button" class="btn btn-outline-warning btn-sm p-1 px-2" data-bs-toggle="modal" data-bs-target="#update_modal<?php echo $row['id']; ?>" title="Edit"><i class="bi bi-pencil"></i></button>
                                        <?php if (!($row['role'] == 'admin')) : ?>
                                            <a href="user-delete.php?id=<?= $row['id']; ?>" class="btn btn-outline-danger btn-sm p-1 px-2" onclick="return confirm('Delete user <?= $row['username']; ?>?');" title="Delete"><i class="bi bi-trash"></i></a>
                                        <?php endif;?>
                                    </div>
                                 </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <!-- Close Container -->

    <!-- Edit Modals (Moved outside loop for z-index/stacking context fix) -->
    <?php foreach ($users_id as $row) : ?>
    <div class="modal fade" id="update_modal<?php echo $row['id']?>" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="fw-bold">Edit User: <?php echo $row['username']; ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-start">
                    <form action="" method="post" enctype="multipart/form-data">
                        <div class="mb-3">
                            <label class="form-label">Username</label>
                            <input type="hidden" name="id" value="<?php echo $row['id']?>"/>
                            <input type="text" class="form-control" name="username" value="<?php echo $row['username']; ?>">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Email</label>
                            <input type="email" class="form-control" name="email" value="<?php echo $row['email']; ?>">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Role</label>
                            <select name="role" class="form-control">
                                <?php 
                                $selection = array('admin', 'user', 'member');
                                foreach ($selection as $sel) {
                                    $selected = ($row['role'] == $sel) ? "selected" : "";
                                    echo '<option '.$selected.' value="'.$sel.'">'.$sel.'</option>';
                                }
                                ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Phone</label>
                            <input type="text" class="form-control" name="phone" value="<?php echo $row['phone']; ?>">
                        </div>
                        <?php if ($row['role'] !== 'admin'): ?>
                        <div class="mb-3">
                            <label class="form-label">Subscription Period</label>
                            <select name="subscription_period" class="form-select">
                                <?php 
                                $periods = array('Tidak Aktif', '1 Minggu', '1 Bulan', '3 Bulan', '6 Bulan', '12 Bulan');
                                foreach ($periods as $p) {
                                    $p_selected = ($row['subscription_period'] == $p) ? "selected" : "";
                                    echo '<option '.$p_selected.' value="'.$p.'">'.$p.'</option>';
                                }
                                ?>
                            </select>
                            <div class="form-text small">Expiry: <?= $row['expiry_date'] ? date('d-m-Y H:i', strtotime($row['expiry_date'])) : 'N/A' ?></div>
                        </div>
                        <?php endif; ?>
                        <div class="mb-3">
                            <label class="form-label">Change Password (Leave blank to keep)</label>
                            <input type="password" class="form-control" name="password" placeholder="**********">
                        </div>
                        <div class="mb-3">
                            <label class="form-label d-block fw-bold">Assignable Events</label>
                            <div class="glass-card p-3" style="max-height: 200px; overflow-y: auto;">
                               <?php 
                               $all_ev = get_all_events();
                               $user_ev = get_user_event_ids($row['id']);
                               foreach($all_ev as $ev): 
                                   $is_checked = in_array($ev['id'], $user_ev) ? 'checked' : '';
                               ?>
                               <div class="form-check mb-2">
                                   <input class="form-check-input" type="checkbox" name="events[]" value="<?= $ev['id'] ?>" id="ev_<?= $row['id'] ?>_<?= $ev['id'] ?>" <?= $is_checked ?>>
                                   <label class="form-check-label small" for="ev_<?= $row['id'] ?>_<?= $ev['id'] ?>">
                                       <?= $ev['acara'] ?> <span class="text-muted">(<?= $ev['tanggal'] ?>)</span>
                                   </label>
                               </div>
                               <?php endforeach; ?>
                            </div>
                        </div>
                        <input type="hidden" name="register_date" value="<?php echo $row['register_date']; ?>">
                        <button type="submit" class="btn btn-primary w-100" name="update">Update User</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
    <!-- Close Container -->

   <!-- Modal AddData -->
    <div class="modal fade" id="AddData" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="fw-bold"><i class="bi bi-person-plus-fill"></i> Add New User</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="addform" action="" method="post" enctype="multipart/form-data">
                        <div class="mb-3">
                            <label class="form-label">Username</label>
                            <input type="text" class="form-control" name="username" placeholder="Username" required autocomplete="off">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Email</label>
                            <input type="email" class="form-control" name="email" placeholder="Email" required autocomplete="off">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Role</label>
                            <select name="role" class="form-control">
                                <option value="user">user</option>
                                <option value="member">member</option>
                                <option value="admin">admin</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Phone</label>
                            <input type="text" class="form-control" name="phone" placeholder="Phone Number" required autocomplete="off">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Subscription Period</label>
                            <select name="subscription_period" class="form-select">
                                <option value="Tidak Aktif">Tidak Aktif</option>
                                <option value="1 Minggu">1 Minggu</option>
                                <option value="1 Bulan">1 Bulan</option>
                                <option value="3 Bulan">3 Bulan</option>
                                <option value="6 Bulan">6 Bulan</option>
                                <option value="12 Bulan">12 Bulan</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label d-block fw-bold">Assignable Events</label>
                            <div class="glass-card p-3" style="max-height: 200px; overflow-y: auto;">
                               <?php 
                               $all_ev = get_all_events();
                               foreach($all_ev as $ev): 
                               ?>
                               <div class="form-check mb-2">
                                   <input class="form-check-input" type="checkbox" name="events[]" value="<?= $ev['id'] ?>" id="new_ev_<?= $ev['id'] ?>">
                                   <label class="form-check-label small" for="new_ev_<?= $ev['id'] ?>">
                                       <?= $ev['acara'] ?> <span class="text-muted">(<?= $ev['tanggal'] ?>)</span>
                                   </label>
                               </div>
                               <?php endforeach; ?>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary w-100" name="simpan">Save User</button>
                        <div class="mt-3 text-center text-muted small">Default Password: <b>user123</b></div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <!-- Close Modal AddData -->

<?php if (isset($_POST['update'])) {
    if (user_update_admin($_POST) > 0) {
        echo '<script>swal("Success!", "User updated successfully!", "success").then(() => { window.location="user.php"; });</script>';
    } else {
        echo '<script>swal("Error!", "Failed to update user.", "error");</script>';
    }
}?>

    <!-- Bootstrap -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#data').dataTable({
                "lengthChange": false, 
                "paging": true,
                 "language": {
                    "search": "",
                    "searchPlaceholder": "Search users..."
                },
                 "dom": "<'row'<'col-sm-12 col-md-6'l><'col-sm-12 col-md-6'f>>" +
                   "<'row'<'col-sm-12'tr>>" +
                   "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
            });
        });
    </script>
    
</body>
</html>