<?php
session_start();

// Database connection parameters
$host    = 'localhost';
$dbUser  = 'root';
$dbPass  = '';
$dbName  = 'lpt_db';

// Create connection
$conn = new mysqli($host, $dbUser, $dbPass, $dbName);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Handle AJAX request for fetching seniors
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'fetch_seniors') {
    header('Content-Type: application/json');
    $username = trim($_POST['username']);
    $stmt = $conn->prepare(
        "SELECT um.id, um.userid,um.role, m1.fullname AS asm_name, m2.fullname AS zsm_name
         FROM usermaster um
         JOIN usermaster m1 ON um.manager_id = m1.userid
         JOIN usermaster m2 ON m1.manager_id = m2.userid
         WHERE um.userid = ? AND um.Userstatus = 'active'"
    );
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result && $result->num_rows === 1) {
        $row = $result->fetch_assoc();
        $_SESSION['id']  = $row['id'];
        $_SESSION['user_id']  = $row['userid'];
        $_SESSION['username'] = $username;
        $_SESSION['role']     = $row['role'];
        echo json_encode(['success' => true, 'asm_name' => $row['asm_name'], 'zsm_name' => $row['zsm_name']]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid or inactive Employee code.']);
    }
    $stmt->close();
    $conn->close();
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Login</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
  <div class="container d-flex justify-content-center align-items-center vh-100">
    <div class="card shadow-sm" style="width: 100%; max-width: 400px;">
      <div class="card-body">
        <h3 class="card-title text-center mb-4">Employee Login</h3>
        <form id="loginForm">
          <!-- Step 1: Enter Employee Code -->
          <div id="step1">
            <div class="mb-3">
              <label for="username" class="form-label">Employee Code</label>
              <input type="text" class="form-control" id="username" name="username" required>
            </div>
            <button id="nextBtn" class="btn btn-primary w-100" type="button">Next</button>
          </div>

          <!-- Step 2: Display ASM and ZSM -->
          <div id="step2" class="d-none">
            <div class="mb-3">
              <label class="form-label">ASM (Senior)</label>
              <input type="text" class="form-control" id="asmName" disabled>
            </div>
            <div class="mb-3">
              <label class="form-label">ZSM (Senior)</label>
              <input type="text" class="form-control" id="zsmName" disabled>
            </div>
            <button id="gotoDashboard" class="btn btn-success w-100" type="button">Go to Dashboard</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- Consent Modal -->
  <div class="modal fade" id="consentModal" tabindex="-1" aria-labelledby="consentModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="consentModalLabel">Consent Required</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <p>Please confirm your consent to proceed to the dashboard.</p>
          <div class="form-check">
            <input class="form-check-input" type="checkbox" value="" id="consentCheckbox">
            <label class="form-check-label" for="consentCheckbox">
              I agree
            </label>
          </div>
        </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="confirmConsent">Proceed</button>
        </div>
      </div>
    </div>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    document.getElementById('nextBtn').addEventListener('click', function() {
      const username = document.getElementById('username').value.trim();
      if (!username) {
        alert('Please enter Employee Code');
        return;
      }
      fetch('', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({ action: 'fetch_seniors', username })
      })
      .then(res => res.json())
      .then(data => {
        if (data.success) {
          document.getElementById('asmName').value = data.asm_name;
          document.getElementById('zsmName').value = data.zsm_name;
          document.getElementById('nextBtn').classList.add('d-none');
          document.getElementById('step2').classList.remove('d-none');
        } else {
          alert(data.message);
        }
      }).catch(() => alert('Error fetching senior details.'));
    });

    document.getElementById('gotoDashboard').addEventListener('click', function() {
      const consentModal = new bootstrap.Modal(document.getElementById('consentModal'));
      consentModal.show();
    });

    document.getElementById('confirmConsent').addEventListener('click', function() {
      const checkbox = document.getElementById('consentCheckbox');
      if (checkbox.checked) {
        window.location.href = 'tm-dashboard.php';
      } else {
        alert('Please agree before proceeding.');
      }
    });
  </script>
</body>
</html>