<?php
require_once 'config/auth.php';
require_once 'config/db.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Ensure user context is loaded
if (!isset($_SESSION['user'])) {
    header("Location: index.php");
    exit();
}
$user = $_SESSION['user'];

// Restrict access to Admins, Management, and Sales roles
$user_role    = strtolower(trim($user['role'] ?? 'user'));
$isAdmin      = ($user_role === 'admin');
$isManagement = in_array($user_role, ['management', 'admin']);
$isManager    = ($user_role === 'manager');
$isSales      = in_array($user_role, ['sales', 'sales team']);
$isServerTeam = in_array($user_role, ['server_team', 'server team']);
$isUser       = ($user_role === 'user');

// Page-Level Guard: Allow Sales, Management, and Admins
if (!$isSales && !$isManagement && !$isAdmin) {
    $_SESSION['error'] = "You do not have permission to access the Manage Aliases page.";
    header("Location: index.php");
    exit();
}

$message = '';
$messageType = '';

// 1. Handle Form Insert Request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_alias') {
    $class        = trim($_POST['class'] ?? '');
    $server_alias = trim($_POST['server_alias'] ?? '');

    if (empty($class) || empty($server_alias)) {
        $message = "Please fill in all required fields.";
        $messageType = "danger";
    } else {
        $stmt = $conn->prepare("INSERT INTO salestemp (class, server_alias) VALUES (?, ?)");
        $stmt->bind_param("ss", $class, $server_alias);
        
        if ($stmt->execute()) {
            $message = "Server Alias added successfully!";
            $messageType = "success";
        } else {
            $message = "Database insert error: " . $stmt->error;
            $messageType = "danger";
        }
        $stmt->close();
    }
}

// 2. Handle Delete Request
if (isset($_GET['delete_id'])) {
    $delete_id = (int)$_GET['delete_id'];
    
    if ($delete_id > 0) {
        $stmt = $conn->prepare("DELETE FROM salestemp WHERE id = ?");
        $stmt->bind_param("i", $delete_id);
        
        if ($stmt->execute()) {
            $message = "Server Alias deleted successfully!";
            $messageType = "success";
        } else {
            $message = "Delete failed: " . $stmt->error;
            $messageType = "danger";
        }
        $stmt->close();
    }
}

// 3. Fetch Big Class and Small Class Records
$bigClassResult   = $conn->query("SELECT * FROM salestemp WHERE class = 'Bigclass' ORDER BY id DESC");
$smallClassResult = $conn->query("SELECT * FROM salestemp WHERE class = 'Smallclass' ORDER BY id DESC");
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo htmlspecialchars($_SESSION['user']['company_name'] ?? 'Dashboard'); ?> | Manage Aliases</title>
<link rel="icon" type="image/x-icon" href="<?php echo htmlspecialchars($_SESSION['user']['fav'] ?? ''); ?>">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.3.3/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.11.3/font/bootstrap-icons.min.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/style.css">
</head>
<body class="dash-body">

<div class="sidebar-backdrop"></div>

<!-- ===================== SIDEBAR ===================== -->
<aside class="sidebar">
  <a href="#" class="sidebar-brand text-decoration-none">
    <img src="<?php echo htmlspecialchars($_SESSION['user']['logo']); ?>" alt="company" width="150">
  </a>
  
  <nav class="sidebar-nav">
    <div class="sidebar-section-label">MAIN</div>
    
    <!-- ================= 1. SERVER REQUIREMENT DROPDOWN ================= -->
     
    <div class="nav-item">
      <a class="nav-link dropdown-toggle d-flex align-items-center justify-content-between" 
         href="#menuRequirement" 
         data-bs-toggle="collapse" 
         role="button" 
         aria-expanded="false" 
         aria-controls="menuRequirement">
        <span><i class="bi bi-file-earmark-plus me-2"></i>New Server</span>
      </a>
      <div class="collapse submenu-wrap ps-3" id="menuRequirement">
        <?php if (!$isSales && !$isServerTeam): ?>
		<a href="new-server-requirement.php" class="nav-link submenu-link">
          Requirement
        </a>
		<?php endif; ?> 
		<a href="new-server-status.php" class="nav-link submenu-link">
          Status
        </a>
        
      </div>
    </div>
    
    
    <!-- ================= 2. SERVER STATUS DROPDOWN ================= -->
	<?php if (!$isServerTeam): ?>
    <div class="nav-item">
      <a class="nav-link dropdown-toggle d-flex align-items-center justify-content-between active" 
         href="#menuStatus" 
         data-bs-toggle="collapse" 
         role="button" 
         aria-expanded="true" 
         aria-controls="menuStatus">
        <span><i class="bi bi-list-check me-2"></i>Existing Server</span>
      </a>
      <div class="collapse show submenu-wrap ps-3" id="menuStatus">
		<?php if (!$isSales && !$isServerTeam): ?>
       <a href="existing-server-requirement.php" class="nav-link submenu-link">
           Requirement
        </a>
		 <?php endif; ?>
        <a href="existing-server-status.php" class="nav-link submenu-link">
           Status
        </a>
		
		<?php if($isSales): ?> 
       <a href="manage_alias.php" class="nav-link submenu-link subactive">
           Add Alias
        </a>
		 <?php endif; ?>
		
      </div>
    </div>
	<?php endif; ?>
	
    <!-- ================= 3. MANAGEMENT ================= -->
    <?php if($isManagement || $isAdmin): ?>
      <div class="sidebar-section-label mt-3">MANAGEMENT</div>
      <a href="manage-users.php" class="nav-link"><i class="bi bi-people me-2"></i> Manage Users</a>
    <?php endif; ?>
  </nav>

  <div class="sidebar-footer">
    <div class="mt-4 small text-center text-muted">
      <small>Developed by - Redaries</small>
    </div>
  </div>
</aside>

<!-- ===================== MAIN WRAPPER ===================== -->
<div class="main-wrap">
  <div class="topbar d-flex justify-content-between align-items-center">
    <div class="d-flex align-items-center gap-3">
      <button class="btn btn-menu btn-outline-secondary d-md-none"><i class="bi bi-list"></i></button>
      <div>
        <div class="fw-bold fs-5">Manage Server Aliases</div>
        <div class="breadcrumb-mini text-muted small">Dashboard / Manage Aliases</div>
      </div>
    </div>
    
    <div class="d-flex align-items-center gap-3">
      <div class="dropdown">
        <button class="btn btn-light dropdown-toggle d-flex align-items-center gap-2 border" type="button" data-bs-toggle="dropdown" aria-expanded="false">
          <i class="bi bi-person-circle text-primary fs-5"></i>
          <span class="fw-semibold small"><?php echo htmlspecialchars($user['username'] ?? 'User'); ?></span>
        </button>

        <ul class="dropdown-menu dropdown-menu-end shadow-sm border-0">
          <li>
            <a class="dropdown-item text-danger d-flex align-items-center gap-2" href="logout.php">
              <i class="bi bi-box-arrow-right"></i> Logout
            </a>
          </li>
        </ul>
      </div> 
    </div>
  </div>

  <div class="page-content p-4">

    <!-- Flash Notifications -->
    <?php if (!empty($message)): ?>
      <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show mb-4" role="alert">
        <i class="bi bi-info-circle-fill me-2"></i>
        <?php echo $message; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
      </div>
    <?php endif; ?>

    <div class="row g-4">
      
      <!-- LEFT SIDE: Form to Insert Data -->
      <div class="col-lg-5">
        <div class="card border-0 shadow-sm rounded-3">
          <div class="card-header bg-white py-3 border-bottom">
            <h6 class="fw-bold mb-0 text-primary"><i class="bi bi-plus-circle me-2"></i>Add New Server Alias</h6>
          </div>
          <div class="card-body p-4">
            <form action="manage_alias.php" method="POST">
              <input type="hidden" name="action" value="add_alias">

              <div class="mb-3">
                <label class="form-label fw-semibold small">Class <span class="text-danger">*</span></label>
                <select name="class" id="class" class="form-select" required>
                  <option value="">Select Class</option>
                  <option value="Bigclass">Big Class</option>
                  <option value="Smallclass">Small Class</option>
                </select>
              </div>

              <div class="mb-4">
                <label class="form-label fw-semibold small">Server Alias <span class="text-danger">*</span></label>
                <input type="text" name="server_alias" class="form-control" placeholder="Enter Server Alias" required>
              </div>

              <button type="submit" class="btn btn-primary w-100">
                <i class="bi bi-save me-1"></i> Insert Server Alias
              </button>
            </form>
          </div>
        </div>
      </div>

<!-- RIGHT SIDE: Display Tables (Tabbed layout for Big & Small Class) -->
<div class="col-lg-7">
  <div class="card border-0 shadow-sm rounded-3 overflow-hidden">
    <!-- Tab Navigation Header -->
    <div class="card-header bg-white py-3 border-bottom">
      <ul class="nav nav-tabs card-header-tabs" id="aliasTabs" role="tablist">
        <li class="nav-item" role="presentation">
          <button class="nav-link active fw-bold text-dark d-flex align-items-center gap-2" id="bigclass-tab" data-bs-toggle="tab" data-bs-target="#bigclass-pane" type="button" role="tab" aria-controls="bigclass-pane" aria-selected="true">
            <i class="bi bi-hdd-stack text-primary"></i> Big Class 
            <span class="badge bg-primary rounded-pill"><?php echo $bigClassResult ? $bigClassResult->num_rows : 0; ?></span>
          </button>
        </li>
        <li class="nav-item" role="presentation">
          <button class="nav-link fw-bold text-dark d-flex align-items-center gap-2" id="smallclass-tab" data-bs-toggle="tab" data-bs-target="#smallclass-pane" type="button" role="tab" aria-controls="smallclass-pane" aria-selected="false">
            <i class="bi bi-cpu text-secondary"></i> Small Class 
            <span class="badge bg-secondary rounded-pill"><?php echo $smallClassResult ? $smallClassResult->num_rows : 0; ?></span>
          </button>
        </li>
      </ul>
    </div>

    <div class="card-body p-0">
      <div class="tab-content" id="aliasTabsContent">
        
        <!-- BIG CLASS TABLE PANE -->
        <div class="tab-pane fade show active" id="bigclass-pane" role="tabpanel" aria-labelledby="bigclass-tab">
          <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
              <thead class="table-light">
                <tr class="text-uppercase small text-muted">
                  <th style="width: 8%;" class="ps-3">#</th>
                  <th style="width: 25%;">Class</th>
                  <th>Server Alias</th>
                  <th class="text-end pe-3" style="width: 20%;">Action</th>
                </tr>
              </thead>
              <tbody>
                <?php if ($bigClassResult && $bigClassResult->num_rows > 0): ?>
                  <?php $idx = 1; while ($row = $bigClassResult->fetch_assoc()): ?>
                    <tr>
                      <td class="ps-3 text-muted fw-semibold"><?php echo $idx++; ?></td>
                      <td>
                        <span class="badge bg-primary-subtle text-primary border border-primary-subtle px-2 py-1">
                          <?php echo htmlspecialchars($row['class']); ?>
                        </span>
                      </td>
                      <td class="fw-semibold text-dark">
                        <i class="bi bi-server text-muted me-2"></i><?php echo htmlspecialchars($row['server_alias']); ?>
                      </td>
                      <td class="text-end pe-3">
                        <a href="manage_alias.php?delete_id=<?php echo $row['id']; ?>" 
                           class="btn btn-sm btn-outline-danger px-2 py-1"
                           onclick="return confirm('Are you sure you want to delete this Server Alias?');"
                           title="Delete Alias">
                          <i class="bi bi-trash"></i> Delete
                        </a>
                      </td>
                    </tr>
                  <?php endwhile; ?>
                <?php else: ?>
                  <tr>
                    <td colspan="4" class="text-center py-5 text-muted">
                      <i class="bi bi-inbox fs-2 text-secondary d-block mb-2"></i>
                      No Big Class server aliases found.
                    </td>
                  </tr>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>

        <!-- SMALL CLASS TABLE PANE -->
        <div class="tab-pane fade" id="smallclass-pane" role="tabpanel" aria-labelledby="smallclass-tab">
          <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
              <thead class="table-light">
                <tr class="text-uppercase small text-muted">
                  <th style="width: 8%;" class="ps-3">#</th>
                  <th style="width: 25%;">Class</th>
                  <th>Server Alias</th>
                  <th class="text-end pe-3" style="width: 20%;">Action</th>
                </tr>
              </thead>
              <tbody>
                <?php if ($smallClassResult && $smallClassResult->num_rows > 0): ?>
                  <?php $idx = 1; while ($row = $smallClassResult->fetch_assoc()): ?>
                    <tr>
                      <td class="ps-3 text-muted fw-semibold"><?php echo $idx++; ?></td>
                      <td>
                        <span class="badge bg-secondary-subtle text-secondary border border-secondary-subtle px-2 py-1">
                          <?php echo htmlspecialchars($row['class']); ?>
                        </span>
                      </td>
                      <td class="fw-semibold text-dark">
                        <i class="bi bi-server text-muted me-2"></i><?php echo htmlspecialchars($row['server_alias']); ?>
                      </td>
                      <td class="text-end pe-3">
                        <a href="manage_alias.php?delete_id=<?php echo $row['id']; ?>" 
                           class="btn btn-sm btn-outline-danger px-2 py-1"
                           onclick="return confirm('Are you sure you want to delete this Server Alias?');"
                           title="Delete Alias">
                          <i class="bi bi-trash"></i> Delete
                        </a>
                      </td>
                    </tr>
                  <?php endwhile; ?>
                <?php else: ?>
                  <tr>
                    <td colspan="4" class="text-center py-5 text-muted">
                      <i class="bi bi-inbox fs-2 text-secondary d-block mb-2"></i>
                      No Small Class server aliases found.
                    </td>
                  </tr>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>

      </div>
    </div>
  </div>
</div>

    </div>

  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.3.3/js/bootstrap.bundle.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>