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

require_role('admin','hr','trainer'); // trainers can create their own
global $pdo;

$errors = [];
$title = $description = '';
$schedule = '';
$date_from = ''; 
$date_to= '';
$trainee='';
$trainer_id = null;

// Trainers default to themselves; Admin/HR can pick any trainer
if (current_user()['role'] === 'trainer') {
  $trainer_id = (int)current_user()['id'];
}

// Load trainers for dropdown
$trainers = $pdo->query("SELECT id, name FROM users WHERE role='trainer' AND status='active' ORDER BY name ASC")->fetchAll();


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  verify_csrf();
  $title = trim($_POST['title'] ?? '');
  $description = trim($_POST['description'] ?? '');
  $schedule = trim($_POST['schedule'] ?? '');
   $date_from = trim($_POST['date_from'] ?? '');
    $date_to = trim($_POST['date_to'] ?? '');
	 $trainee = trim($_POST['trainee'] ?? '');
	 $selectionfor = trim($_POST['selectionfor'] ?? '');
	  $selectionlnd = trim($_POST['selectionlnd'] ?? '');
	 
  $trainer_id = (int)($_POST['trainer_id'] ?? 0) ?: null;

  if ($title === '' || mb_strlen($title) < 3) $errors['title'] = 'Title must be at least 3 characters.';
  if ($schedule !== '' && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $schedule)) $errors['schedule'] = 'Schedule must be YYYY-MM-DD or blank.';




  if (empty($errors)) {
    $stmt = $pdo->prepare("INSERT INTO training (title, description, schedule, trainer_id, date_from, date_to,traineename,leveloftraining,lnd) VALUES (?,?,?,?,?,?,?,?,?)");
    $stmt->execute([$title, $description, $schedule ?: null, $trainer_id, $date_from, $date_to,$trainee,$selectionfor,$selectionlnd]);
    set_flash('success', 'Training created.');
    header('Location: /ldp/public/trainings/index.php');
    exit;
  }
}

render_header('Create Training', 'trainings');
?>
<div class="card">
  <div class="card-body">
    <form method="post" autocomplete="off" novalidate>
      <?= csrf_field(); ?>
      <div class="form-group">
        <label class="form-required">Training Title of L&D</label>
        <input name="title" class="form-control <?= isset($errors['title'])?'is-invalid':'' ?>" value="<?= htmlspecialchars($title) ?>">
        <?php if(isset($errors['title'])): ?><div class="invalid-feedback"><?= htmlspecialchars($errors['title']) ?></div><?php endif; ?>
      </div>

      <div class="form-group">
        <label>Training Description</label>
        <textarea name="description" rows="4" class="form-control"><?= htmlspecialchars($description) ?></textarea>
      </div>

 <div class="form-group">
        <label>Category</label>
        <select name="selectionfor" class="form-control">
              <option value="">Select Trainings Levels</option>
                <option value="National">National</option>
                <option value="International">International</option>
				<option value="Local">Local</option>
				<option value="Regional">Regional</option>
				<option value="All">All</option>
            </select>
      </div>
<div class="form-group">
        <label>Type of L&D</label>
        <select name="selectionlnd" class="form-control">
              <option value="">Select LND Levels</option>
                <option value="Technical">Technical</option>
                <option value="Ledearship">Leadership</option>
				<option value="Supervisory">Supervisory</option>
				
				<option value="All">All</option>
            </select>
      </div>

      <div class="form-row">
        <div class="form-group col-md-6">
          <label>Training Schedule DATE FROM(YYYY-MM-DD)</label>
          <input type="date" name="date_from" placeholder="e.g. 2025-09-10" class="form-control" value="<?= htmlspecialchars($date_from)?>">
        </div>
		 <div class="form-group col-md-6">
          <label>Training Schedule DATE TO(YYYY-MM-DD)</label>
          <input type="date" name="date_to" placeholder="e.g. 2025-09-10" class="form-control" value="<?= htmlspecialchars($date_to)?>">
         
        </div>
		 <div class="form-group col-md-6">
          <label>Select Trainee</label>
            <select name="trainee" class="form-control">
              <option value="">Select Trainee</option>
              <?php 

$con = mysqli_connect("127.0.0.1","root","","ldp_db");
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 personnel")or die(mysqli_error($con));
	while($row=mysqli_fetch_array($query)){
           $id=$row['id'];
           $name=$row['name'];
			  ?>
                <option value="<?php echo $row['id']; ?>"><?php echo $row['name'];?> </option>
	<?php } ?>
            </select>
         
        </div>
        <div class="form-group col-md-6">
          <label>Select Trainer</label>
          <select name="trainee" class="form-control">
              <option value="">Select Trainer if no add in personnel=employee type trainer </option>
              <?php 

$con = mysqli_connect("127.0.0.1","root","","ldp_db");
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
  date_default_timezone_set("Asia/Manila");
			  $query2=mysqli_query($con,"select * from personnel where employee_type='Trainer'")or die(mysqli_error($con));
	while($row2=mysqli_fetch_array($query2)){
           $id=$row2['id'];
           $name2=$row2['name'];
			  ?>
                <option value="<?php echo $row2['id']; ?>"><?php echo $row2['name'];?> </option>
	<?php } ?>
            </select>
        </div>
      </div>

      <div class="d-flex justify-content-between">
        <a href="/ldp/public/trainings/index.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left"></i> Back</a>
        <button class="btn btn-primary"><i class="fas fa-save"></i> Save</button>
      </div>
    </form>
  </div>
</div>
<?php render_footer(); ?>
