<?php
// public/reports/personnel.php
declare(strict_types=1);
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/layout.php';
require_once __DIR__ . '/../../includes/flash.php';

require_login();
$user = current_user();

// Only admin/hr can view reports
if (!in_array($user['role'], ['admin','hr'], true)) {
    set_flash('danger', 'You are not authorized to access reports.');
    header('Location: /ldp/public/dashboard.php');
    exit;
}

global $pdo;

$q       = trim($_GET['search'] ?? '');
$year    = trim($_GET['year'] ?? '');

$params = [];
$where  = [];

// keyword search
if ($q !== '') {
    $where[] = "(employee_id LIKE :q1
              OR name LIKE :q2
              OR position LIKE :q3
              OR employee_type LIKE :q4
              OR status LIKE :q5
              OR address LIKE :q6
              OR cpnumber LIKE :q7
              OR type LIKE :q8
              OR level LIKE :q9)";
    $params = array_merge($params, [
        ':q1' => "%$q%",
        ':q2' => "%$q%",
        ':q3' => "%$q%",
        ':q4' => "%$q%",
        ':q5' => "%$q%",
        ':q6' => "%$q%",
        ':q7' => "%$q%",
        ':q8' => "%$q%",
        ':q9' => "%$q%",
    ]);
}


$sql = "SELECT * FROM personnel";
if ($where) {
    $sql .= " WHERE " . implode(" AND ", $where);
}
$sql .= " ORDER BY updated_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();


render_header('Personnel Report', 'reports');
$flash = get_flash();
if ($flash): ?>

<style>
 @media print {
          .btn-print {
            display:none !important;
          }
		  .card2 {
			  display:none !important;
		  }
		  .btn-danger {
			   display:none !important;
		  }
		  .met {
			  display:none !important;
		  }
		  .mr-2 {
			  display:none !important;
		  }
      }

  
</style>

  <div class="alert alert-<?= htmlspecialchars($flash['type'] ?? '') ?>">
    <?= htmlspecialchars($flash['message'] ?? '') ?>
  </div>
<?php endif; ?>

<div class="card">
  
  
<form method="POST" class="met">
      <div class="input-group mr-2">
      <input type="text" id="searchInput" style="width:400px;font-size:18px;" onkeyup="myFunction()" placeholder="Search for Names,Type,And Year..">
       <input type="text" id="searchInput" style="width:90px;font-size:18px;" onkeyup="myFunction()" placeholder="Year..">
      
	  </div>

     
      <div class="input-group-append">
        <button type="submit" class="btn btn-outline-secondary"><i class="fas fa-search">Click to Search</i></button>
        <a href="personnel.php" class="btn btn-outline-dark">Reset</a>
      </div>
    </form>

    <!-- Export buttons -->
    <div class="ml-2">
      <?php
      // keep same filters in export links
      $query = http_build_query([
        'search' => $q,
      ]);
      ?>
      <a href="export_personnel.php?format=pdf&<?= $query ?>" class="btn btn-sm btn-danger"><i class="fas fa-file-pdf"></i> Export PDF</a>
      <!--<a href="export_personnel.php?format=excel&<?= $query ?>" class="btn btn-sm btn-success"><i class="fas fa-file-excel"></i> Export Excel</a> -->
    
	</div>
   <a class = "btn btn-success btn-print" href = "" onclick = "window.print()"><i class ="glyphicon glyphicon-print"></i> Print</a>
	

  <div class="card-body p-0">
    <div class="table-responsive">
	<br></br>
	<table class="header">
    <tr>
        <td><img src="http://localhost/ldp/public/assets/img/logo.png" alt="Logo" style="width:90px;height:90px;border-raduis:50%;" class="brand-image img-circle elevation-3"></td>
        <td style="width: 70%;">
            Republic of the Philippines<br>
            <strong>DR. EMILIO B. ESPINOSA SR., MEMORIAL STATE COLLEGE OF AGRICULTURE AND TECHNOLOGY</strong><br>
            Cabitan, Mandaon, Masbate | <a href="http://www.debesmscat.edu.ph">www.debesmscat.edu.ph</a><br>
            <strong style="font-size:23px;">PERSONNEL REPORTS</strong>
        </td>
        
        <td style="width: 15%;">
            
            <img src="http://localhost/ldp/public/assets/img/l.png" alt="mylogo" style="width:90px;height:90px;">
        </td>
    </tr>
</table>
	
	
      <table class="table table-striped mb-0" id="myTable">
        <thead>
          <tr>
         
            <th>Name</th>
            <th>Position</th>
            <th>Employee Type</th>
            <th>Status</th>
			<th>Category</th>
			 <th>Year and Day</th>
             <!-- <th>Address</th>
            <th>Cp Number</th>
            <th>Date</th>
            <th>Type</th>
            <th>Level</th> -->
          </tr>
        </thead>
        <tbody>

          <?php if (!$rows): ?>
            <tr><td colspan="10" class="text-center text-muted p-4">No personnel records found.</td></tr>
          <?php else: foreach ($rows as $p): 
		  $babykop=$p['id']?? null;
		  
		  ?>
            <tr>
             
              <td><?= htmlspecialchars($p['name'] ?? '') ?></td>
              <td><?= htmlspecialchars($p['position'] ?? '') ?></td>
              <td>
                <?php if (!empty($p['employee_type'])): ?>
                  <span class="badge badge-info"><?= htmlspecialchars($p['employee_type']) ?></span>
                <?php endif; ?>
              </td>
              <td>
                <?php if (!empty($p['status'])): 
                  $statusClass = 'secondary';
                  if ($p['status'] === 'Permanent') $statusClass = 'success';
                  elseif (stripos($p['status'], 'Contract') !== false) $statusClass = 'warning';
                  elseif (stripos($p['status'], 'Job Order') !== false) $statusClass = 'info';
                ?>
                  <span class="badge badge-<?= $statusClass ?>">
                    <?= htmlspecialchars($p['status']) ?>
                  </span>
                <?php endif; ?>
              </td>
			  <?php
			  $con = mysqli_connect("localhost","root","","ldp_db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

  date_default_timezone_set("Asia/Manila"); 
			    	$query=mysqli_query($con,"select * from training where traineename='$babykop'")or die(mysqli_error($con));
		$row56=mysqli_fetch_array($query);
			  
			  ?>
			  
			  
			  
			  <td><?php echo $row56['leveloftraining']?? null; ?></td>
			  
			  
			  
			  
			   <td><?= htmlspecialchars($p['created_at'] ?? '') ?></td>
              <!-- <td><?= htmlspecialchars($p['address'] ?? '') ?></td>
              <td><?= htmlspecialchars($p['cpnumber'] ?? '') ?></td>
              <td>
                <?php if (!empty($p['date_from']) && !empty($p['date_to'])): ?>
                  <?= htmlspecialchars($p['date_from']) ?> to <?= htmlspecialchars($p['date_to']) ?>
                <?php else: ?>
                  <?= htmlspecialchars($p['updated_at'] ?? '') ?>
                <?php endif; ?>
              </td>
              <td><?= htmlspecialchars($p['traineetype'] ?? '') ?></td>
              <td><?= htmlspecialchars($p['level'] ?? '') ?></td> -->
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
  <script>
    document.getElementById('searchInput').addEventListener('keyup', function() {
      const filter = this.value.toUpperCase();
      const table = document.getElementById('myTable');
      const rows = table.getElementsByTagName('tr');

      for (let i = 1; i < rows.length; i++) { // Skip the header row
        const cells = rows[i].getElementsByTagName('td');
        let match = false;

        for (let j = 0; j < cells.length; j++) {
          if (cells[j]) {
            const text = cells[j].textContent || cells[j].innerText;
            if (text.toUpperCase().indexOf(filter) > -1) {
              match = true;
              break;
            }
          }
        }

        rows[i].style.display = match ? '' : 'none';
      }
    });
  </script>

<?php render_footer(); ?>
