<?php
session_start();
include 'config.php';
include 'zklib/zklib.php'; // Path to zklib.php in zklib folder

// Restrict access (only Admins & Superadmins)
if (!isset($_SESSION['username']) || (!in_array($_SESSION['role'], ['admin', 'superadmin']))) {
    header("Location: index.php");
    exit();
}

// Get selected month or default to current
$selected_month = isset($_GET['month']) ? $_GET['month'] : date('Y-m');

// Initialize ZKLib and fetch biometric users with retry
$biometric_error = '';
$biometric_users = [];
$device_ip = '192.168.10.55'; // Device IP
$device_port = 4370;
$max_retries = 3;
$retry_delay = 1; // seconds
$zk = new ZKLib($device_ip, $device_port);

for ($attempt = 1; $attempt <= $max_retries; $attempt++) {
    $result = $zk->connect();
    if ($result === true) {
        $biometric_users = $zk->getUser();
        $zk->disconnect();
        
        // Sync biometric users to users table
        foreach ($biometric_users as $uid => $user) {
            $userid = $conn->real_escape_string($user['userid']);
            $name = $conn->real_escape_string($user['name']);
            // Check if user exists in users table
            $check_query = "SELECT id FROM users WHERE username = '$userid'";
            $check_result = $conn->query($check_query);
            if ($check_result->num_rows == 0) {
                // Insert new user with minimal data
                $insert_query = "INSERT INTO users (username, first_name, role, status) 
                                 VALUES ('$userid', '$name', 'employee', 'active')";
                $conn->query($insert_query);
                error_log("[" . date('Y-m-d H:i:s') . "] Synced biometric user: $userid from $device_ip");
            }
        }
        break; // Success, exit retry loop
    } else {
        $biometric_error = $result;
        error_log("[" . date('Y-m-d H:i:s') . "] Attempt $attempt/$max_retries: Biometric connection failed to $device_ip:$device_port: $result");
        if ($attempt < $max_retries) {
            sleep($retry_delay);
        }
    }
}

// Enhance error message with manual troubleshooting steps
if ($biometric_error) {
    $biometric_error .= " (Tried $max_retries times. Please check: 1) Is device powered on at $device_ip:$device_port? 2) Run 'telnet $device_ip $device_port' or 'nc -zv $device_ip $device_port' from your server to test connectivity. 3) Verify no firewall blocks port $device_port. 4) Contact hosting provider to ensure outbound TCP connections are allowed.)";
}

// Fetch all active employees (including newly synced biometric users)
$employees_result = $conn->query("SELECT id, username FROM users WHERE role = 'employee' AND status = 'active' ORDER BY username");
$employees = [];
while ($row = $employees_result->fetch_assoc()) {
    $employees[$row['id']] = $row['username'];
}

// Fetch attendance logs from DB (already synced from biometric)
$sql = "
    SELECT a.user_id, a.log_time, a.status, u.username 
    FROM attendance a
    JOIN users u ON a.user_id = u.id
    WHERE DATE_FORMAT(a.log_time, '%Y-%m') = ?
    ORDER BY a.log_time ASC
";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $selected_month);
$stmt->execute();
$result = $stmt->get_result();

// Group by employee
$monthly_attendance = [];
while ($row = $result->fetch_assoc()) {
    $user_id = $row['user_id'];
    $date = date("Y-m-d", strtotime($row['log_time']));
    $time = date("H:i", strtotime($row['log_time']));
    $status = $row['status'];

    if (!isset($monthly_attendance[$user_id])) {
        $monthly_attendance[$user_id] = [
            'username' => $row['username'],
            'logs' => []
        ];
    }
    $monthly_attendance[$user_id]['logs'][$date][] = [
        'time' => $time,
        'status' => $status
    ];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Attendance Dashboard</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body { background: #f4f6f9; }
    .attendance-day {
        display: inline-block;
        width: 28px; height: 28px;
        line-height: 28px;
        text-align: center;
        margin: 2px;
        border-radius: 4px;
        font-size: 0.8rem;
    }
    .in { background: #d4edda; color: #155724; }
    .out { background: #f8d7da; color: #721c24; }
    .empty { background: #e2e3e5; color: #6c757d; }
    .card-header { font-weight: bold; }
    .table-biometric { max-width: 1200px; margin: 0 auto 30px; }
  </style>
</head>
<body>
<div class="container my-4">
  <h2 class="text-center text-primary">Attendance Dashboard</h2>

  <!-- Biometric Users Table -->
  <div class="card mb-4">
    <div class="card-header bg-success text-white">
      <h5>Biometric Users</h5>
    </div>
    <div class="card-body">
      <?php if ($biometric_error): ?>
        <div class="alert alert-danger">
          <?php echo htmlspecialchars($biometric_error); ?>
        </div>
      <?php elseif (empty($biometric_users)): ?>
        <div class="alert alert-warning">
          No biometric users fetched from device. Ensure users are enrolled on the device.
        </div>
      <?php else: ?>
        <table class="table table-bordered table-hover table-sm table-biometric">
          <thead class="table-dark">
            <tr>
              <th>User ID</th>
              <th>Name</th>
              <th>Privilege</th>
              <th>Type</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($biometric_users as $uid => $user): ?>
              <tr>
                <td><?php echo htmlspecialchars($user['userid']); ?></td>
                <td><?php echo htmlspecialchars($user['name']); ?></td>
                <td>
                  <?php
                  $privilege = $user['privilege'];
                  echo $privilege == 14 ? 'Admin' : ($privilege == 0 ? 'User' : $privilege);
                  ?>
                </td>
                <td><?php echo htmlspecialchars($user['type']); ?></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      <?php endif; ?>
    </div>
  </div>

  <!-- Month Selector -->
  <form method="get" class="row g-3 mb-4">
    <div class="col-auto">
      <label for="month" class="col-form-label">Select Month:</label>
    </div>
    <div class="col-auto">
      <input type="month" class="form-control" id="month" name="month"
             value="<?php echo htmlspecialchars($selected_month); ?>" onchange="this.form.submit()">
    </div>
  </form>

  <!-- Monthly Attendance Table -->
  <div class="card mb-4">
    <div class="card-header bg-info text-white">
      <h5>Monthly Attendance Overview - <?php echo date('F Y', strtotime($selected_month)); ?></h5>
    </div>
    <div class="card-body">
      <table class="table table-bordered table-sm">
        <thead class="table-dark">
          <tr>
            <th>Employee</th>
            <th>Attendance</th>
          </tr>
        </thead>
        <tbody>
          <?php
          $days_in_month = date('t', strtotime($selected_month . "-01"));
          foreach ($employees as $emp_id => $emp_name) {
              echo "<tr>";
              echo "<td><b>" . htmlspecialchars($emp_name) . " ($emp_id)</b></td>";
              echo "<td>";
              for ($day = 1; $day <= $days_in_month; $day++) {
                  $date_str = sprintf("%s-%02d", $selected_month, $day);
                  $class = "empty";
                  $title = $date_str . ": No record";

                  if (isset($monthly_attendance[$emp_id]['logs'][$date_str])) {
                      foreach ($monthly_attendance[$emp_id]['logs'][$date_str] as $log) {
                          if ($log['status'] == "IN") {
                              $class = "in";
                              $title = $date_str . " IN @ " . $log['time'];
                          } elseif ($log['status'] == "OUT") {
                              $class = "out";
                              $title = $date_str . " OUT @ " . $log['time'];
                          }
                      }
                  }

                  echo "<span class='attendance-day $class' title='$title'>$day</span>";
              }
              echo "</td></tr>";
          }
          ?>
        </tbody>
      </table>
    </div>
  </div>

  <!-- Raw Attendance Log -->
  <div class="card">
    <div class="card-header bg-secondary text-white">
      <h5>Detailed Logs (<?php echo date('F Y', strtotime($selected_month)); ?>)</h5>
    </div>
    <div class="card-body">
      <table class="table table-bordered table-hover table-sm">
        <thead class="table-dark">
          <tr>
            <th>Date</th>
            <th>Time</th>
            <th>Employee</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody>
          <?php
          foreach ($monthly_attendance as $uid => $data) {
              foreach ($data['logs'] as $date => $logs) {
                  foreach ($logs as $log) {
                      echo "<tr>";
                      echo "<td>$date</td>";
                      echo "<td>" . $log['time'] . "</td>";
                      echo "<td>" . htmlspecialchars($data['username']) . " ($uid)</td>";
                      echo "<td>" . $log['status'] . "</td>";
                      echo "</tr>";
                  }
              }
          }
          ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
