<?php
// public/trainings/view.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();
global $pdo;

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) { header('Location: /ldp/public/trainings/index.php'); exit; }

$stmt = $pdo->prepare("SELECT t.*, u.name AS trainer_name
                       FROM training t
                       LEFT JOIN users u ON u.id = t.trainer_id
                       WHERE t.id = ?");
$stmt->execute([$id]);
$training = $stmt->fetch();
if (!$training) { set_flash('warning','Training not found.'); header('Location:/ldp/public/trainings/index.php'); exit; }

$canManage = in_array($user['role'], ['admin','hr'], true) ||
             ($user['role']==='trainer' && (int)$training['trainer_id']===(int)$user['id']);

$enr = $pdo->prepare("SELECT e.id, e.user_id, e.status, e.completion_date, u.name, u.email
                      FROM enrollment e
                      JOIN users u ON u.id = e.user_id
                      WHERE e.training_id = ?
                      ORDER BY u.name ASC");
$enr->execute([$id]);
$enrollments = $enr->fetchAll();


$employees = [];
if ($canManage) {
  $employees = $pdo->query("SELECT id, name, position, employee_type FROM personnel WHERE employee_type!='trainer' ORDER BY id ASC")->fetchAll();
}

render_header('Training Details', 'trainings');
$flash = get_flash();
if ($flash): ?>
  <div class="alert alert-<?= htmlspecialchars($flash['type']) ?>"><?= htmlspecialchars($flash['message']) ?></div>
<?php endif; ?>
<style>
 @media print {
          .btn-print {
            display:none !important;
          }
		  .card2 {
			  display:none !important;
		  }
		  .mt-3 {
			  display:none !important;
		  }
      }
</style>
<div class="card">
  <div class="card-body">
   <a class = "btn btn-success btn-print" href = "" onclick = "window.print()"><i class ="glyphicon glyphicon-print"></i> Print</a>
  
  
<style>
    body { font-family: DejaVu Sans, Arial, sans-serif; font-size: 18px; }
    .header { width: 100%; border: 1px solid #000; border-collapse: collapse; margin-bottom: 10px; }
    .header td { border: 1px solid #000; text-align: center; vertical-align: middle; }
    .header img { height: 70px; }
    h2 { text-align:center; margin: 8px 0; }
    table { width:100%; border-collapse: collapse; margin-top: 10px; }
    th, td { border:1px solid #333; padding:5px 7px; font-size: 18px; }
    th { background:#f0f0f0; }
</style>

<?php

$logoLeft  = realpath(__DIR__ . '/../../public/assets/logo_left.png');
$logoRight = realpath(__DIR__ . '/../../public/assets/logo_right.png');
 // update path if needed
?>
<table class="header">
    <tr>
        <td style="width: 15%;"><img src="' . $logoLeft . '"></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:25px;">TRAINING REPORTS</strong>
        </td>
        
        <td style="width: 15%;">
            
            <img src="' . $logoRight . '" style="width:15%x; margin-top:10px;">
        </td>
    </tr>
</table>



  
  
  
    <h2 class="mb-1">Title: <?= htmlspecialchars($training['title']) ?></h2>
    <label>Description</label><p class="text-muted mb-2"><?= nl2br(htmlspecialchars($training['description'])) ?></p>
    <div class="row">
      <div class="col-md-4"><strong>Schedule:</strong> <?= htmlspecialchars($training['schedule'] ?: 'MTWTFSS') ?></div>
	   <div class="col-md-4"><strong>Description:</strong> <?= htmlspecialchars($training['description'] ?: 'ALL') ?></div>
	   <div class="col-md-4"><strong>Level of Training:</strong> <?= htmlspecialchars($training['leveloftraining'] ?: 'ALL') ?></div>
	    <div class="col-md-4"><strong>LND:</strong> <?= htmlspecialchars($training['lnd'] ?: 'ALL') ?></div>
      <div class="col-md-4"><strong>Trainer:</strong> <?= htmlspecialchars($training['trainer_name'] ?: 'Unassigned') ?></div>
      <div class="col-md-4"><strong>Created:</strong> <?= htmlspecialchars($training['created_at']) ?></div>
    </div>
  </div>
</div>

<?php if ($canManage): ?>
<div class="card2">
  <div class="card-header"><h3 class="card-title">Enroll Employee</h3></div>
  <div class="card-body">
    <form class="form-inline" method="post" action="enroll.php">
      <?= csrf_field(); ?>
      <input type="hidden" name="training_id" value="<?= (int)$training['id'] ?>">
      <div class="form-group col-md-6">
        <select name="user_id" class="form-control" style="width:500px;">
          <?php foreach ($employees as $emp): ?>
            <option value="<?= (int)$emp['id'] ?>"><?= htmlspecialchars($emp['name'].' ('.$emp['employee_type'].')') ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <button class="btn btn-primary"><i class="fas fa-user-plus"></i> Add / Enroll</button>
    </form>
  </div>
</div>
<?php endif; ?>

<div class="card">
  <div class="card-header"><h3 class="card-title">Enrolled Participants</h3></div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-striped mb-0" style="font-size:16px;">
        <thead>
          <tr>
            <th>Name</th>
            <th>Department</th>
            <th style="width:160px;">Status</th>
            <th style="width:160px;">Completion Date</th>
           <!-- <?php if ($canManage): ?><th style="width:240px;">Actions</th><?php endif; ?> -->
          </tr>
        </thead>
        <tbody>
       <tr>
	   <?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"); 
$baby=(int)$training['id'];
	   $query1=mysqli_query($con,"select * from enrollment where training_id='$baby'")or die(mysqli_error());
		while($row1=mysqli_fetch_array($query1)){
			$mybaby=$row1['user_id'];
			  $query=mysqli_query($con,"select * from personnel where id='$mybaby'")or die(mysqli_error());
		$row=mysqli_fetch_array($query);
						?>
	   
              <td><?php echo $row['name'];?> </td>
              <td><?php echo $row['department'];?> </td>
              <td><?php echo $row1['status'];?> </td>
              <td><?php echo $row1['completion_date'];?> </td>
           
             <!-- <td>
                <form method="post" action="update_status.php" class="form-inline d-inline">
                  <?= csrf_field(); ?>
                  <input type="hidden" name="enrollment_id" value="<?= (int)$e['id'] ?>">
                  <input type="hidden" name="training_id" value="<?= (int)$training['id'] ?>">
                  <select name="status" class="form-control mr-2">
                    <?php foreach (['enrolled','in-progress','completed'] as $st): ?>
                      <option value="<?= $st ?>" <?= $e['status']===$st?'selected':'' ?>><?= ucfirst($st) ?></option>
                    <?php endforeach; ?>
                  </select>
                  <button class="btn btn-sm btn-outline-primary"><i class="fas fa-save"></i></button>
                </form>
                <form method="post" action="unenroll.php" class="d-inline" onsubmit="return confirm('Remove this participant?');">
                  <?= csrf_field(); ?>
                  <input type="hidden" name="enrollment_id" value="<?= (int)$e['id'] ?>">
                  <input type="hidden" name="training_id" value="<?= (int)$training['id'] ?>">
                  <button class="btn btn-sm btn-outline-danger"><i class="fas fa-user-minus"></i></button>
                </form>
              </td> -->
        
            </tr>
		<?php } ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<div class="mt-3">
  <a href="/ldp/public/trainings/index.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left"></i> Back to list</a>
</div>

<?php render_footer(); ?>
