<?php
include("include/conn.php");
include("include/function.php");
$login = cekSession();
if ($login != 1) {
  redirect("login.php");
}
?>
<!DOCTYPE html>
<html class="loading" lang="es" data-textdirection="ltr">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
  <title id="title"><?= $brandName ?> | Todos los Admins</title>
  <link rel="apple-touch-icon" href="assets/images/ico/apple-icon-120.png">
  <link rel="shortcut icon" type="image/x-icon" href="assets/images/ico/favicon.ico">
  <link href="https://fonts.googleapis.com/css?family=Muli:300,300i,400,400i,600,600i,700,700i%7CComfortaa:300,400,700" rel="stylesheet">
  <link href="https://maxcdn.icons8.com/fonts/line-awesome/1.1/css/line-awesome.min.css" rel="stylesheet">
  
  <link rel="stylesheet" type="text/css" href="assets/css/vendors.css">
  <link rel="stylesheet" type="text/css" href="assets/css/app-lite.css">
  <link rel="stylesheet" type="text/css" href="assets/css/core/menu/menu-types/vertical-menu.css">
  <link rel="stylesheet" type="text/css" href="assets/css/core/colors/palette-gradient.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@10/dist/sweetalert2.min.css">
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap4.min.css" />

    <style>
        .content-wrapper { background-color: #f3f4f6; }
        .card {
            border: none;
            border-radius: 12px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        .card-header {
            background-color: transparent;
            border-bottom: 1px solid #e5e7eb;
            padding: 1.5rem;
        }
        .card-title { font-weight: 600; color: #1f2937; }
        .table-responsive { padding: 1.5rem; }
        #adminTable {
            width: 100% !important;
            border-collapse: collapse;
        }
        #adminTable thead th {
            background-color: #f9fafb;
            color: #4b5563;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            border-bottom: 2px solid #e5e7eb;
        }
        #adminTable tbody tr:hover { background-color: #f9fafb; }
        #adminTable td, #adminTable th { vertical-align: middle; }
        div.dataTables_wrapper div.dataTables_filter input,
        .dataTables_length select {
            border-radius: 8px !important;
            border: 1px solid #d1d5db !important;
            padding: 0.5rem 0.75rem !important;
        }
        .license-status {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-weight: 500;
            font-size: 0.75rem;
        }
        .status-live { background-color: #d1fae5; color: #065f46; }
        .status-expired { background-color: #fee2e2; color: #991b1b; }
    </style>

</head>

<body class="vertical-layout vertical-menu 2-columns menu-expanded fixed-navbar" data-open="click" data-menu="vertical-menu" data-color="bg-gradient-x-purple-blue" data-col="2-columns">

  <?php include("include/header.php"); ?>
  <?php include("include/sidebar.php"); ?>

  <div class="app-content content">
    <div class="content-wrapper">
      <div class="content-wrapper-before" style="background: none;"></div>
      <div class="content-header row">
        <div class="content-header-left col-md-4 col-12 mb-2">
          <h3 class="content-header-title" style="color: #1f2937; font-weight: 700;">Todos los Admins</h3>
        </div>
        <div class="content-header-right col-md-8 col-12">
          <div class="breadcrumbs-top float-md-right">
            <div class="breadcrumb-wrapper mr-1">
              <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="index.php">Inicio</a></li>
                <li class="breadcrumb-item active">Todos los Admins</li>
              </ol>
            </div>
          </div>
        </div>
      </div>
      <div class="content-body">
        <div class="row">
          <div class="col-12">
            <div class="card">
              <div class="card-header">
                <h4 class="card-title">Gestión de Administradores</h4>
              </div>
                <div class="table-responsive">
                  <table class="table table-hover" id="adminTable">
                    <thead>
                      <tr>
                        <th>Usuario</th>
                        <th>Nombre</th>
                        <th>Contacto</th>
                        <th>Estado</th>
                        <th>Fecha Inicio</th>
                        <th>Fecha Expiración</th>
                        <th>Acción</th>
                      </tr>
                    </thead>
                    <tbody>
                      <?php
                      if ($_SESSION['user_type'] == 'admin') {
                        $q = mysqli_query($conn, "SELECT `id`,`username`, `name`, `contact_number`, `password`, `user_type`,`start_date`, `expired_date`, `status` FROM `admin` WHERE `user_type` = 'user' AND `deleted` != 'yes'");
                      } else {
                        $u_id = $_SESSION['id'];
                        $q = mysqli_query($conn, "SELECT `id`,`username`, `name`, `contact_number`, `password`, `user_type`,`start_date`, `expired_date`, `status` FROM `admin` WHERE `user_type` = 'user' AND `deleted` != 'yes'AND `admin_id` = '$u_id'");
                      }

                      while ($row = mysqli_fetch_assoc($q)) {
                        $id = $row['id'];
                        echo '<tr>';
                        echo '<td>' . htmlspecialchars($row['username']) . '</td>';
                        echo '<td>' . htmlspecialchars($row['name']) . '</td>';
                        echo '<td>' . htmlspecialchars($row['contact_number']) . '</td>';
                        
                        $statusClass = $row['status'] == 'true' ? 'status-live' : 'status-expired';
                        $statusText = $row['status'] == 'true' ? 'Activo' : 'Expirado';
                        echo '<td><span class="license-status ' . $statusClass . '">' . $statusText . '</span></td>';

                        echo '<td>' . date('d/m/Y', strtotime($row['start_date'])) . '</td>';
                        echo '<td>' . date('d/m/Y', strtotime($row['expired_date'])) . '</td>';
                        echo '<td>
                              <div class="btn-group">
                                  <button type="button" class="btn btn-sm btn-outline-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Acción</button>
                                  <div class="dropdown-menu dropdown-menu-right">
                                      <a class="dropdown-item activate-btn" href="#" data-id="' . $id . '"><i class="la la-check text-success"></i> Activar</a>
                                      <a class="dropdown-item deactivate-btn" href="#" data-id="' . $id . '"><i class="la la-times text-warning"></i> Desactivar</a>
                                      <div class="dropdown-divider"></div>
                                      <a class="dropdown-item change-password-btn" href="#" data-id="' . $id . '"><i class="la la-key"></i> Cambiar Contraseña</a>
                                      <div class="dropdown-divider"></div>
                                      <a class="dropdown-item delete-btn" href="#" data-id="' . $id . '"><i class="la la-trash text-danger"></i> Eliminar</a>
                                  </div>
                              </div>
                            </td>';
                        echo '</tr>';
                      }
                      ?>
                    </tbody>
                  </table>
                </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <?php include("include/footer.php"); ?>
  
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap4.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>
  <script src="assets/js/core/app-menu-lite.js" type="text/javascript"></script>
  <script src="assets/js/core/app-lite.js" type="text/javascript"></script>

  <script>
    $(document).ready(function() {
      $('#title').html('<?= $brandName ?> | Todos los Admins');
      $("#sid-rall").addClass("active"); // Assuming this is correct sidebar ID

      $('#adminTable').DataTable({
        "paging": true,
        "ordering": true,
        "searching": true,
        "order": [[4, "desc"]], // Order by start date
        "columnDefs": [{ "orderable": false, "targets": 6 }],
        "language": { "url": "//cdn.datatables.net/plug-ins/1.11.5/i18n/es-ES.json" }
      });

      // Action handlers
      $(document).on('click', '.activate-btn', function() { updateUserStatus($(this).data('id'), 'true'); });
      $(document).on('click', '.deactivate-btn', function() { updateUserStatus($(this).data('id'), 'false'); });
      $(document).on('click', '.delete-btn', function() { deleteUser($(this).data('id')); });
      $(document).on('click', '.change-password-btn', function() { changePassword($(this).data('id')); });
    });

    function updateUserStatus(id, status) {
        $.post('function/update_status.php', { id: id, status: status }, function(response) {
            Swal.fire('Estado Actualizado', response.message, 'success').then(() => location.reload());
        }, 'json').fail(() => Swal.fire('Error', 'Ocurrió un error.', 'error'));
    }

    function deleteUser(id) {
        Swal.fire({
            title: '¿Estás seguro?', text: "Esta acción marcará al admin como eliminado.",
            icon: 'warning', showCancelButton: true, confirmButtonColor: '#d33',
            confirmButtonText: 'Sí, ¡eliminar!', cancelButtonText: 'Cancelar'
        }).then((result) => {
            if (result.isConfirmed) {
                $.post('function/delete_admin.php', { id: id }, function(response) {
                    Swal.fire('¡Eliminado!', response.message, 'success').then(() => location.reload());
                }, 'json').fail(() => Swal.fire('Error', 'Ocurrió un error.', 'error'));
            }
        });
    }

    function changePassword(id) {
        const newPassword = Math.floor(100000 + Math.random() * 900000).toString();
        $.post('function/update_password.php', { id: id, password: newPassword }, function() {
            Swal.fire('Nueva Contraseña Generada', 'Nueva Contraseña: ' + newPassword, 'success');
        }).fail(() => Swal.fire('Error', 'Ocurrió un error al cambiar la contraseña.', 'error'));
    }
  </script>
</body>
</html>
