<?php
session_start();
include("connect.php") ;
// 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']); $_SESSION["last_url"]="form-login.php";
    
    $stmt = $conn->prepare(
        "SELECT um.id, um.userid, um.role             
                
         FROM usermaster um
         
         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'];
        $_SESSION['formtype']="form";    
        echo json_encode([
            'success' => true
           
            
        ]);
    } 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">
  <link href="css/styles.css" rel="stylesheet">
</head>
<body>
<div class="container bg2">
  <header>
    <div class="row align-items-center">
      <div class="col-6 text-start">
        <a href="#">
          <img src="images/lpt-left-logo.png" class="img-fluid" alt="Left logo">
        </a>
      </div>
      <div class="col-6 text-end">
        <img src="images/topmenu-logo.png" class="img-fluid" alt="Topmenu logo">
      </div>
    </div>
  </header>

  <div class="content mt-3">
    <form id="loginForm" method="post">
      <!-- Step 1: Enter Employee Code -->
      <div id="step1">
        <div class="mb-3">
          <label for="username" class="form-label">User Code</label>
          <input type="text" class="form-control" id="username" name="username" required>
        </div>
        <div class="row">
            <div class="col-3 col-md-2"></div>
            <div class="col-6 col-md-6"><center>
            <input type="image" id="nextBtn" src="images/login_btn2.png" class="img-fluid" alt="Login" />
          </center></div>
           <div class="col-3 col-md-2">  </div>
       </div>
      </div>

      <!-- Step 2: Display ASM and ZSM-->
      <div id="step2" class="d-none">
       
     <!--  <div class="mb-3">
          <label class="form-label">ZBM (Senior)</label>
          <input type="text" class="form-control" id="zbmName" disabled>
        </div>-->

        <div class="row">
            <div class="col-3 col-md-2"></div>
            <div class="col-6 col-md-6"> <center> <button id="gotoDashboard" class="btn  w-100" type="button"><img src="images/submit_btn.png"></button> </center></div>
           <div class="col-3 col-md-2">  </div>
       </div>

      
      </div>
    </form>
  </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" 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>

  <footer>
    <div class="row">
      <div class="col-6 col-md-6 padding-zero text-center" style="background:#ECE9F8">
      <div class="mt-4"><a href="#"  data-bs-toggle="modal" data-bs-target="#findUserModal" style="color:#54308E;font-weight:bold;text-decoration:none;"> Find Your User Code</a></div>
      </div>
      <div class="col-6 col-md-6 padding-zero contact-us text-center" style="background:#54308E">
      <img src="images/contact-us.png" class="img-fluid" style="cursor:pointer;" data-bs-toggle="modal" data-bs-target="#contactModal">
      </div>
    </div>
  </footer>
</div>




<!-- Contact Us Modal -->
<div class="modal fade" id="contactModal" tabindex="-1" aria-labelledby="contactModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="contactModalLabel">Contact Us</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
      <p><strong>Name:</strong> Ravindra Veer</p>
        <p><strong>Support Email:</strong> ravindra.veer@exicongroup.com</p>
        <p><strong>Phone:</strong> +91-9284759607,+91-8446704280 (Whatsapp) </p>
        <p><strong>Contact Time:</strong> Time, 9 AM to 6 PM</p>
        <!-- Add any other contact details here -->
      </div>
    </div>
  </div>
</div>



<!-- Find User Code Modal -->
<div class="modal fade" id="findUserModal" tabindex="-1" aria-labelledby="findUserModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="findUserModalLabel">Find Your User Code</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
      <div class="mb-3">
  <label for="fullnameInput" class="form-label">Full Name (partial allowed)</label>
  <input type="text" class="form-control" id="fullnameInput" placeholder="Enter full or partial name">
</div>
<div class="mb-3">
  <label for="stateInput" class="form-label">State (partial allowed)</label>
  <input type="text" class="form-control" id="stateInput" placeholder="Enter full or partial state">
</div>
        <div id="userDetails" class="d-none">
          <p><strong>User ID:</strong> <span id="userId"></span></p>
          <p><strong>Full Name:</strong> <span id="fullName"></span></p>
          <p><strong>State:</strong> <span id="userState"></span></p>
        </div>
        <div id="userError" class="text-danger d-none">TM ID not found.</div>
      </div>
      <div class="modal-footer">
        <button type="button" id="fetchUserBtn" class="btn btn-primary">Fetch Details</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(e) {
    e.preventDefault(); // stop form from submitting normally
    const username = document.getElementById('username').value.trim(); 

    if (!username) {
      alert('Please enter User Code');
      return;
    }

    fetch('form-login.php', {   // Correct PHP file name
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({ action: 'fetch_seniors', username: username })
    })
    .then(response => response.json())
    .then(data => {  
      if (data.success) {   
        //document.getElementById('asmName').value = data.asm_name; 
     //   document.getElementById('zbmName').value = data.zbm_name;  
        document.getElementById('nextBtn').classList.add('d-none');
        // document.getElementById('step1').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 = 'form-dashboard.php';
    } else {
      alert('Please agree before proceeding.');
    }
  });
</script>


<script>
document.getElementById('fetchUserBtn').addEventListener('click', function () {
  const fullname = document.getElementById('fullnameInput').value.trim();
  const state = document.getElementById('stateInput').value.trim();

  if (!fullname && !state) {
    alert('Please enter Full Name or State to search.');
    return;
  }

  fetch('get-user-by-tmid.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({ fullname, state })
  })
  .then(res => res.json())
  .then(data => {
    const userDetails = document.getElementById('userDetails');
    const userError = document.getElementById('userError');

    if (data.success) {
      let output = '<ul class="list-group">';
      data.data.forEach(user => {
        output += `<li class="list-group-item">
          <strong>User ID:</strong> ${user.userid}<br>
          <strong>Full Name:</strong> ${user.fullname}<br>
          <strong>State:</strong> ${user.state}
        </li>`;
      });
      output += '</ul>';
      userDetails.innerHTML = output;
      userDetails.classList.remove('d-none');
      userError.classList.add('d-none');
    } else {
      userDetails.classList.add('d-none');
      userError.textContent = data.message || 'No users found.';
      userError.classList.remove('d-none');
    }
  })
  .catch(() => {
    alert('Something went wrong. Please try again.');
  });
});

</script>
</body>
</html>
