<?php
require_login
();

$wfId intval($_GET['wf'] ?? 0);
// Get first state
$sql "SELECT pk_State, title FROM TICKET_State WHERE fk_Workflow = ? ORDER BY `no` ASC LIMIT 1";
$stmt mysqli_prepare($conn$sql);
mysqli_stmt_bind_param($stmt'i'$wfId);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt$stateId$stateTitle);
if (!
mysqli_stmt_fetch($stmt)) exit('Invalid workflow');
mysqli_stmt_close($stmt);

// Get workflow title
$wfSql "SELECT title FROM TICKET_Workflow WHERE pk_Workflow = ?";
$wfStmt mysqli_prepare($conn$wfSql);
mysqli_stmt_bind_param($wfStmt'i'$wfId);
mysqli_stmt_execute($wfStmt);
mysqli_stmt_bind_result($wfStmt$workflowTitle);
mysqli_stmt_fetch($wfStmt);
mysqli_stmt_close($wfStmt);

// Get fields
$fSql 'SELECT id_field, label, type, is_optional FROM TICKET_Field WHERE fk_State = ?';
$fStmt mysqli_prepare($conn$fSql);
mysqli_stmt_bind_param($fStmt'i'$stateId);
mysqli_stmt_execute($fStmt);
$fRes mysqli_stmt_get_result($fStmt);
?>
<div class="page-request-fill">
  <div class="page-header">
    <h1 class="page-title"><?= htmlspecialchars($workflowTitle?></h1>
    <p class="page-subtitle">Fill out the form to start your request</p>
  </div>
  
  <form method="post" action="index.php?page=request_submit">
    <input type="hidden" name="wf" value="<?= $wfId ?>">
    <input type="hidden" name="state" value="<?= $stateId ?>">
    
    <?php while ($field mysqli_fetch_assoc($fRes)): ?>
      <label>
        <?= htmlspecialchars($field['label']) ?>
        <?php if (!$field['is_optional']): ?>
          <span style="color: var(--error-color);">*</span>
        <?php endif; ?>
        
        <?php if ($field['type']==='input'||$field['type']==='text'): ?>
          <input type="text" name="field_<?= $field['id_field'?><?php if (!$field['is_optional']) echo 'required'?>>
        <?php elseif ($field['type']==='date'): ?>
          <input type="date" name="field_<?= $field['id_field'?><?php if (!$field['is_optional']) echo 'required'?>>
        <?php elseif ($field['type']==='number'): ?>
          <input type="number" name="field_<?= $field['id_field'?><?php if (!$field['is_optional']) echo 'required'?>>
        <?php elseif ($field['type']==='checkbox'): ?>
          <input type="checkbox" name="field_<?= $field['id_field'?>" style="width: auto; margin-right: 0.5rem;">
        <?php endif; ?>
      </label>
    <?php endwhile; ?>
    
    <button type="submit">Submit Request</button>
  </form>
</div>