<?php
require_login
();
require_admin();

$wfId intval($_REQUEST['wf'] ?? 0);
if (!
$wfId) {
    exit(
'Invalid workflow ID');
}

// Process POST – update workflow + states + fields + actors
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
mysqli_begin_transaction($conn);

    
// 1) Update workflow title
    
$newTitle trim($_POST['workflow_title']);
    
$u1 mysqli_prepare($conn'UPDATE TICKET_Workflow SET title = ? WHERE pk_Workflow = ?');
    
mysqli_stmt_bind_param($u1'si'$newTitle$wfId);
    
$ok mysqli_stmt_execute($u1);
    
mysqli_stmt_close($u1);

    
// 2) Loop over each state
    
foreach ($_POST['state_id'] as $i => $stateId) {
        
// 2a) Update state title
        
$stateTitle trim($_POST['state_title'][$i]);
        
$u2 mysqli_prepare($conn'UPDATE TICKET_State SET title = ? WHERE pk_State = ?');
        
mysqli_stmt_bind_param($u2'si'$stateTitle$stateId);
        
$ok $ok && mysqli_stmt_execute($u2);
        
mysqli_stmt_close($u2);

        
// 2b) Update actor in one statement
        
$actorType $_POST['actor_type'][$i];
        
$fkUser    = ($actorType === 'USER'  && !empty($_POST['actor_user'][$i]))  ? intval($_POST['actor_user'][$i])  : null;
        
$fkGroup   = ($actorType === 'GROUP' && !empty($_POST['actor_group'][$i])) ? intval($_POST['actor_group'][$i]) : null;

        
$u3 mysqli_prepare(
            
$conn,
            
'UPDATE TICKET_StateActor
                 SET actorType = ?, fk_User = ?, fk_Group = ?
               WHERE fk_State = ?'
        
);
        
mysqli_stmt_bind_param($u3'siii'$actorType$fkUser$fkGroup$stateId);
        
$ok $ok && mysqli_stmt_execute($u3);
        
mysqli_stmt_close($u3);

        
// 2c) Update fields in this state
        
if (!empty($_POST['field_id'][$i])) {
            foreach (
$_POST['field_id'][$i] as $j => $fieldId) {
                
$label      trim($_POST['field_label'][$i][$j]);
                
$type       $_POST['field_type'][$i][$j];
                
$isOptional = isset($_POST['field_optional'][$i][$j]) ? 0;

                
$u4 mysqli_prepare(
                    
$conn,
                    
'UPDATE TICKET_Field SET label = ?, type = ?, is_optional = ? WHERE id_field = ?'
                
);
                
mysqli_stmt_bind_param($u4'ssii'$label$type$isOptional$fieldId);
                
$ok $ok && mysqli_stmt_execute($u4);
                
mysqli_stmt_close($u4);
            }
        }
    }

    
// 3) Commit or rollback with error diagnostics
    
if ($ok) {
        
mysqli_commit($conn);
        
$successMessage 'Workflow updated successfully.';
    } else {
        
$dbErr mysqli_error($conn);
        
mysqli_rollback($conn);
        
$errorMessage 'An error occurred; changes not saved. MySQL said: ' htmlspecialchars($dbErr);
    }
}

// GET: load existing workflow data
$q1 mysqli_prepare($conn'SELECT title FROM TICKET_Workflow WHERE pk_Workflow = ?');
mysqli_stmt_bind_param($q1'i'$wfId);
mysqli_stmt_execute($q1);
mysqli_stmt_bind_result($q1$workflowTitle);
mysqli_stmt_fetch($q1);
mysqli_stmt_close($q1);

// States
$q2 mysqli_prepare(
  
$conn,
  
'SELECT pk_State, no, title FROM TICKET_State WHERE fk_Workflow = ? ORDER BY no ASC'
);
mysqli_stmt_bind_param($q2'i'$wfId);
mysqli_stmt_execute($q2);
mysqli_stmt_bind_result($q2$stateId$stateNo$stateTitle);
$states = [];
while (
mysqli_stmt_fetch($q2)) {
  
$states[] = ['id' => $stateId'no' => $stateNo'title' => $stateTitle];
}
mysqli_stmt_close($q2);

// Fetch fields and actors per state
foreach ($states as &$st) {
  
// Fields
  
$f mysqli_prepare($conn'SELECT id_field, label, type, is_optional FROM TICKET_Field WHERE fk_State = ?');
  
mysqli_stmt_bind_param($f'i'$st['id']);
  
mysqli_stmt_execute($f);
  
$res mysqli_stmt_get_result($f);
  
$st['fields'] = mysqli_fetch_all($resMYSQLI_ASSOC);
  
mysqli_stmt_close($f);

  
// Actor
  
$a mysqli_prepare($conn'SELECT actorType, fk_User, fk_Group FROM TICKET_StateActor WHERE fk_State = ?');
  
mysqli_stmt_bind_param($a'i'$st['id']);
  
mysqli_stmt_execute($a);
  
mysqli_stmt_bind_result($a$actorType$fkUser$fkGroup);
  
mysqli_stmt_fetch($a);
  
mysqli_stmt_close($a);
  
$st['actor'] = ['type' => $actorType'user_id' => $fkUser'group_id' => $fkGroup];
}
unset(
$st);  // break reference so each state keeps its own actor data

// Prepare dropdown data arrays
$allUsers = [];
$ur mysqli_query($conn'SELECT pk_User, firstName, lastName FROM TICKET_User');
while (
$u mysqli_fetch_assoc($ur)) {
  
$allUsers[] = $u;
}
$allGroups = [];
$gr mysqli_query($conn'SELECT pk_Group, name FROM TICKET_Group');
while (
$g mysqli_fetch_assoc($gr)) {
  
$allGroups[] = $g;
}
?>

<div class="page-workflows-edit">
  <div class="page-header">
    <a href="index.php?page=workflows" class="back-link">← Back to Workflows</a>
    <h1 class="page-title">Edit Workflow</h1>
  </div>

  <?php if (isset($successMessage)): ?>
    <div class="success-message"><?= htmlspecialchars($successMessage?></div>
  <?php endif; ?>
  <?php if (isset($errorMessage)): ?>
    <div class="error-message"><?= htmlspecialchars($errorMessage?></div>
  <?php endif; ?>

  <form method="post" class="edit-form">
    <input type="hidden" name="wf" value="<?= htmlspecialchars($wfId?>">

    <div class="workflow-title-group">
      <label class="form-label">Workflow Title</label>
      <input type="text" name="workflow_title" required class="workflow-title-input" value="<?= htmlspecialchars($workflowTitle?>">
    </div>

    <?php foreach ($states as $i => $st): ?>
      <fieldset class="state-fieldset">
        <legend class="state-legend">State <?= htmlspecialchars($st['no']) ?></legend>
        <input type="hidden" name="state_id[<?= $i ?>]" value="<?= htmlspecialchars($st['id']) ?>">

        <div class="state-title-group">
          <label class="form-label">State Title</label>
          <input type="text" name="state_title[<?= $i ?>]" required class="state-title-input" value="<?= htmlspecialchars($st['title']) ?>">
        </div>

        <div class="fields-section">
          <h4 class="section-title">📝 Fields</h4>
          <?php foreach ($st['fields'] as $j => $f): ?>
            <div class="field-row">
              <input type="hidden" name="field_id[<?= $i ?>][<?= $j ?>]" value="<?= htmlspecialchars($f['id_field']) ?>">
              <div class="form-group">
                <label class="form-label">Label</label>
                <input type="text" name="field_label[<?= $i ?>][<?= $j ?>]" required class="form-input" value="<?= htmlspecialchars($f['label']) ?>">
              </div>
              <div class="form-group">
                <label class="form-label">Type</label>
                <select name="field_type[<?= $i ?>][<?= $j ?>]" class="form-select">
                  <?php foreach (['input','checkbox','date','text','number'] as $opt): ?>
                    <option value="<?= $opt ?><?php if ($f['type'] == $opt) echo 'selected'?>><?= ucfirst($opt?></option>
                  <?php endforeach; ?>
                </select>
              </div>
              <div class="form-group">
                <label class="form-label">Optional</label>
                <input type="checkbox" name="field_optional[<?= $i ?>][<?= $j ?>]" <?= $f['is_optional'] ? 'checked' '' ?>>
              </div>
            </div>
          <?php endforeach; ?>
        </div>

        <div class="actor-section">
          <h4 class="section-title">👤 Responsible Actor</h4>
          <div class="form-group">
            <label class="form-label">Type</label>
            <select name="actor_type[<?= $i ?>]" class="form-select">
              <option value="USER" <?php if ($st['actor']['type'] === 'USER') echo 'selected'?>>User</option>
              <option value="GROUP" <?php if ($st['actor']['type'] === 'GROUP') echo 'selected'?>>Group</option>
            </select>
          </div>
          <div class="form-group">
            <label class="form-label">User</label>
            <select name="actor_user[<?= $i ?>]" class="form-select">
              <option value="">--None--</option>
              <?php foreach ($allUsers as $u): ?>
                <option value="<?= htmlspecialchars($u['pk_User']) ?><?php if ($u['pk_User'] == $st['actor']['user_id']) echo 'selected'?>>
                  <?= htmlspecialchars($u['firstName'].' '.$u['lastName']) ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="form-group">
            <label class="form-label">Group</label>
            <select name="actor_group[<?= $i ?>]" class="form-select">
              <option value="">--None--</option>
              <?php foreach ($allGroups as $g): ?>
                <option value="<?= htmlspecialchars($g['pk_Group']) ?><?php if ($g['pk_Group'] == $st['actor']['group_id']) echo 'selected'?>>
                  <?= htmlspecialchars($g['name']) ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>
      </fieldset>
    <?php endforeach; ?>

    <button type="submit" class="save-button">Save Changes</button>
  </form>
</div>