<?php
session_start();
include("connect.php");

// Handle AJAX request for fetching user and senior details
if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['action']) &&
    $_POST['action'] === 'fetch_seniors'
) {
    header('Content-Type: application/json');
    $username = trim($_POST['username']);
    $_SESSION['last_url'] = 'abr-login.php';

    // First, fetch user and designation
    $stmt = $conn->prepare(
        "SELECT id, userid, role, designation FROM usermaster
         WHERE userid = ? AND Userstatus = 'active'"
    );
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result && $result->num_rows === 1) {
        $user = $result->fetch_assoc();
        // Store session values
        $_SESSION['id']          = $user['id'];
        $_SESSION['user_id']     = $user['userid'];
        $_SESSION['username']    = $user['userid'];
        $_SESSION['role']        = $user['role'];
        $_SESSION['designation'] = $user['designation'];
        $_SESSION['formtype']="abr";

        // If TM, fetch manager (ASM) and senior manager (ZSM)
        if ($user['designation'] === 'TM') {
            $stmt2 = $conn->prepare(
                "SELECT
                    tm.tm_id,
                    tm.fullname,
                    tm.state,
                    m1.fullname AS asm_name,
                    m2.fullname AS zsm_name
                 FROM usermaster tm
                 JOIN usermaster m1 ON tm.manager_id = m1.userid
                 JOIN usermaster m2 ON m1.manager_id = m2.userid
                 WHERE tm.userid = ? AND tm.Userstatus = 'active'"
            );
            $stmt2->bind_param("s", $username);
            $stmt2->execute();
            $seniorResult = $stmt2->get_result();

            if ($seniorResult && $seniorResult->num_rows === 1) {
                $senior = $seniorResult->fetch_assoc();
                echo json_encode([
                    'success'     => true,
                    'designation' => 'TM',
                    'tm_id'       => $senior['tm_id'],
                    'fullname'    => $senior['fullname'],
                    'state'       => $senior['state'],
                    'asm_name'    => $senior['asm_name'],
                    'zsm_name'    => $senior['zsm_name'],
                ]);
                $stmt2->close();
                $stmt->close();
                $conn->close();
                exit;
            }
            $stmt2->close();
        }

        // If ABM or ZBM, no seniors needed
        echo json_encode([
            'success'     => true,
            'designation' => $user['designation']
        ]);
        $stmt->close();
        $conn->close();
        exit;
    }
    // Invalid or inactive
    echo json_encode([
        'success' => false,
        'message' => 'Invalid or inactive User 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">
  <style>
    .form-label.mb-0 { font-size:14px; }
    .form-control { font-size:14px; }
  </style>
</head>
<body>
<div class="container bg2">
  <header class="py-3">
    <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-4">
    <form id="loginForm" class="container">

      <!-- Step 1: Employee Code -->
      <div id="step1">
        <div class="row align-items-center mb-3">
          <div class="col-4 text-end">
            <label for="username" class="form-label mb-0">User Code</label>
          </div>
          <div class="col-8">
            <input type="text" class="form-control" id="username" name="username" required>
          </div>
        </div>
        <div class="row text-center">
          <div class="col-2"></div>
          <div class="col-8">
            <button id="nextBtn" type="button" class="btn p-0">
              <img src="images/login_btn2.png" class="img-fluid" alt="Next">
            </button>
          </div>
          <div class="col-2"></div>
        </div>
      </div>

      <!-- Step 2: TM Details -->
      <div id="step2" class="d-none">
        <div class="row align-items-center mb-3">
          <div class="col-4 text-end"><label class="form-label mb-0">TM ID</label></div>
          <div class="col-8"><input type="text" class="form-control" id="tmId" disabled></div>
        </div>
        <div class="row align-items-center mb-3">
          <div class="col-4 text-end"><label class="form-label mb-0">TM Name</label></div>
          <div class="col-8"><input type="text" class="form-control" id="tmName" disabled></div>
        </div>
        <div class="row align-items-center mb-3">
          <div class="col-4 text-end"><label class="form-label mb-0">TM HQ</label></div>
          <div class="col-8"><input type="text" class="form-control" id="tmCity" disabled></div>
        </div>
        <div class="row align-items-center mb-3">
          <div class="col-4 text-end"><label class="form-label mb-0">ASM Name</label></div>
          <div class="col-8"><input type="text" class="form-control" id="asmName" disabled></div>
        </div>
        <div class="row align-items-center mb-4">
          <div class="col-4 text-end"><label class="form-label mb-0">ZSM Name</label></div>
          <div class="col-8"><input type="text" class="form-control" id="zsmName" disabled></div>
        </div>
        <div class="row text-center">
          <div class="col-2"></div>
          <div class="col-8">
            <button id="gotoDashboard" type="button" class="btn p-0">
              <img src="images/submit_btn.png" class="img-fluid" alt="Proceed">
            </button>
          </div>
          <div class="col-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"></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 class="mt-4">
    <div class="row">
      <div class="col-6 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 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>
// Step 1: Fetch user + (if TM) seniors
document.getElementById('nextBtn').addEventListener('click', function(e) {
  e.preventDefault();
  const username = document.getElementById('username').value.trim();
  if (!username) return alert('Please enter User Code');

  fetch('abr-login.php', {
    method: 'POST',
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    body: new URLSearchParams({ action: 'fetch_seniors', username })
  })
  .then(r => r.json())
  .then(data => {
    if (!data.success) return alert(data.message);

    if (data.designation === 'TM') {
      document.getElementById('tmId').value    = data.tm_id;
      document.getElementById('tmName').value  = data.fullname;
      document.getElementById('tmCity').value  = data.state;
      document.getElementById('asmName').value = data.asm_name;
      document.getElementById('zsmName').value = data.zsm_name;
      document.getElementById('step1').classList.add('d-none');
      document.getElementById('step2').classList.remove('d-none');
    } else {
      new bootstrap.Modal(document.getElementById('consentModal')).show();
    }
  })
  .catch(() => alert('Error fetching details.'));
});

// Proceed to dashboard on consent
document.getElementById('gotoDashboard').addEventListener('click', () => {
  new bootstrap.Modal(document.getElementById('consentModal')).show();
});
document.getElementById('confirmConsent').addEventListener('click', () => {
  if (!document.getElementById('consentCheckbox').checked) {
    return alert('Please agree before proceeding.');
  }
  window.location.href = 'abr-dashboard.php';
});
</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>
