<?php
require_login
();
require_admin();

// Retrieve title and num_states
$title     $_REQUEST['title'] ?? '';
$numStates intval($_REQUEST['num_states'] ?? 0);

// Load groups and users
$groups = [];
$gRes mysqli_query($conn'SELECT pk_Group, name FROM TICKET_Group');
while (
$g mysqli_fetch_assoc($gRes)) $groups[] = $g;
$users = [];
$uRes mysqli_query($conn'SELECT pk_User, firstName, lastName FROM TICKET_User');
while (
$u mysqli_fetch_assoc($uRes)) $users[] = $u;

// Determine step
$step $_POST['step'] ?? '';
if (
$step === 'define_states') {
    
$stage 'fields';
} elseif (
$step === 'define_fields') {
    
$stage 'process';
} else {
    
$stage 'states';
}

// Process creation
if ($stage === 'process') {
    
$errors = [];
    
// validate actor and field counts
    
for ($i 1$i <= $numStates$i++) {
        
$actorType  $_POST["actorType_$i"]  ?? '';
        
$actorUser  $_POST["actorUser_$i"]  ?? '';
        
$actorGroup $_POST["actorGroup_$i"] ?? '';
        
$fc intval($_POST["fields_count_$i"] ?? 0);
        if (
$actorType === 'USER' && $actorUser === '') {
            
$errors[] = "State #$i: select a user.";
        }
        if (
$actorType === 'GROUP' && $actorGroup === '') {
            
$errors[] = "State #$i: select a group.";
        }
        if (
$fc 1) {
            
$errors[] = "State #$i: must have at least 1 field.";
        }
    }
    if (empty(
$errors)) {
        
// insert workflow
        
$stmt mysqli_prepare($conn'INSERT INTO TICKET_Workflow (title, iam_inserted) VALUES (?, ?)');
        
mysqli_stmt_bind_param($stmt'si'$title$_SESSION['user_id']);
        
mysqli_stmt_execute($stmt);
        
$wfId mysqli_insert_id($conn);
        
mysqli_stmt_close($stmt);
        
// insert states, fields, actors
        
for ($i 1$i <= $numStates$i++) {
            
// state
            
$stTitle $_POST["state_title_$i"];
            
$stmt mysqli_prepare($conn'INSERT INTO TICKET_State (fk_Workflow, `no`, title) VALUES (?, ?, ?)');
            
mysqli_stmt_bind_param($stmt'iis'$wfId$i$stTitle);
            
mysqli_stmt_execute($stmt);
            
$stateId mysqli_insert_id($conn);
            
mysqli_stmt_close($stmt);
            
// fields
            
$fc intval($_POST["fields_count_$i"]);
            for (
$f 1$f <= $fc$f++) {
                
$lbl $_POST["field_{$i}_{$f}_label"];
                
$typ $_POST["field_{$i}_{$f}_type"];
                
$opt = isset($_POST["field_{$i}_{$f}_optional"]) ? 0;
                
$stmt mysqli_prepare($conn'INSERT INTO TICKET_Field (fk_State, label, type, is_optional) VALUES (?, ?, ?, ?)');
                
mysqli_stmt_bind_param($stmt'issi'$stateId$lbl$typ$opt);
                
mysqli_stmt_execute($stmt);
                
mysqli_stmt_close($stmt);
            }
            
// actor
            
$actorType  $_POST["actorType_$i"];
            
$fkUser     = ($actorType === 'USER')  ? intval($_POST["actorUser_$i"])  : null;
            
$fkGroup    = ($actorType === 'GROUP') ? intval($_POST["actorGroup_$i"]) : null;
            
$stmt mysqli_prepare($conn'INSERT INTO TICKET_StateActor (fk_State, fk_User, fk_Group, actorType) VALUES (?, ?, ?, ?)');
            
mysqli_stmt_bind_param($stmt'iiis'$stateId$fkUser$fkGroup$actorType);
            
mysqli_stmt_execute($stmt);
            
mysqli_stmt_close($stmt);
        }
        echo 
'<div class="page-workflows-define">';
        echo 
'<div style="background: #f0fdf4; color: var(--success-color); padding: 1rem; border-radius: var(--radius-md); border: 1px solid #bbf7d0; margin-bottom: 2rem;">Workflow created successfully!</div>';
        echo 
'<p><a href="index.php?page=workflows" class="btn btn-primary">Back to Workflows</a></p>';
        echo 
'</div>';
        exit;
    }
    
$stage 'fields';
}

// Render forms
?>
<div class="page-workflows-define">
  <div class="page-header">
    <h1 class="page-title">Define "<?= htmlspecialchars($title?>"</h1>
    <p class="page-subtitle">Configure states, fields, and actors for your workflow</p>
  </div>

<?php if ($stage === 'states'): ?>
  <form method="post" class="define-form">
    <input type="hidden" name="step" value="define_states">
    <input type="hidden" name="title" value="<?= htmlspecialchars($title?>">
    <input type="hidden" name="num_states" value="<?= $numStates ?>">
    
    <?php for ($i 1$i <= $numStates$i++): ?>
      <fieldset class="state-fieldset">
        <legend class="state-legend">State #<?= $i ?></legend>
        <div class="form-row">
          <div class="form-group">
            <label class="form-label">Title</label>
            <input type="text" name="state_title_<?= $i ?>" class="form-input" required>
          </div>
          <div class="form-group">
            <label class="form-label">Number of Fields</label>
            <input type="number" name="fields_count_<?= $i ?>" class="form-input" min="1" required value="1">
          </div>
        </div>
      </fieldset>
    <?php endfor; ?>
    
    <button type="submit" class="submit-button">Next: Define Fields & Actors</button>
  </form>

<?php elseif ($stage === 'fields'): ?>
  <?php if (!empty($errors)): ?>
    <div class="error-list">
      <ul>
        <?php foreach ($errors as $error): ?>
          <li><?= htmlspecialchars($error?></li>
        <?php endforeach; ?>
      </ul>
    </div>
  <?php endif; ?>
  
  <form method="post" class="define-form">
    <input type="hidden" name="step" value="define_fields">
    <input type="hidden" name="title" value="<?= htmlspecialchars($title?>">
    <input type="hidden" name="num_states" value="<?= $numStates ?>">
    
    <?php for ($i 1$i <= $numStates$i++): 
        
// preserve prior counts and titles
        
$fc intval($_POST["fields_count_$i"] ?? 1);
        
$st htmlspecialchars($_POST["state_title_$i"] ?? "State $i");
    
?>
      <input type="hidden" name="state_title_<?= $i ?>" value="<?= $st ?>">
      <input type="hidden" name="fields_count_<?= $i ?>" value="<?= $fc ?>">
      
      <fieldset class="state-fieldset">
        <legend class="state-legend">State #<?= $i ?><?= $st ?></legend>
        
        <div class="fields-section">
          <h4 class="section-title">📝 Fields</h4>
          <?php for ($f 1$f <= $fc$f++): ?>
            <div class="field-section">
              <div class="field-title">Field <?= $f ?></div>
              <div class="field-row">
                <div class="form-group">
                  <label class="form-label">Label</label>
                  <input type="text" name="field_<?= $i ?>_<?= $f ?>_label" class="form-input" required>
                </div>
                <div class="form-group">
                  <label class="form-label">Type</label>
                  <select name="field_<?= $i ?>_<?= $f ?>_type" class="form-select">
                    <?php foreach (['input','checkbox','date','text','number'] as $opt): ?>
                      <option value="<?= $opt ?>"><?= ucfirst($opt?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="form-group">
                  <div class="checkbox-group">
                    <input type="checkbox" name="field_<?= $i ?>_<?= $f ?>_optional" id="opt_<?= $i ?>_<?= $f ?>">
                    <label for="opt_<?= $i ?>_<?= $f ?>">Optional</label>
                  </div>
                </div>
              </div>
            </div>
          <?php endfor; ?>
        </div>
        
        <div class="actor-section">
          <div class="actor-title">👤 Responsible Actor</div>
          <div class="actor-row">
            <div class="form-group">
              <label class="form-label">Actor Type</label>
              <select name="actorType_<?= $i ?>" class="form-select">
                <option value="USER">User</option>
                <option value="GROUP">Group</option>
              </select>
            </div>
            <div class="form-group">
              <label class="form-label">User</label>
              <select name="actorUser_<?= $i ?>" class="form-select">
                <option value="">--None--</option>
                <?php foreach ($users as $u): ?>
                  <option value="<?= $u['pk_User'?>"><?= htmlspecialchars($u['firstName'].' '.$u['lastName']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="form-group">
              <label class="form-label">Group</label>
              <select name="actorGroup_<?= $i ?>" class="form-select" disabled style="opacity: 0.5;">
                <option value="">--None--</option>
                <?php foreach ($groups as $g): ?>
                  <option value="<?= $g['pk_Group'?>"><?= htmlspecialchars($g['name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
        </div>
      </fieldset>
    <?php endfor; ?>
    
    <button type="submit" class="submit-button">Create Workflow</button>
  </form>
<?php endif; ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Function to toggle actor dropdowns based on type selection
    function toggleActorDropdowns(stateIndex) {
        const actorTypeSelect = document.querySelector(`select[name="actorType_${stateIndex}"]`);
        const userSelect = document.querySelector(`select[name="actorUser_${stateIndex}"]`);
        const groupSelect = document.querySelector(`select[name="actorGroup_${stateIndex}"]`);
        
        if (actorTypeSelect && userSelect && groupSelect) {
            const selectedType = actorTypeSelect.value;
            
            if (selectedType === 'USER') {
                userSelect.disabled = false;
                userSelect.style.opacity = '1';
                groupSelect.disabled = true;
                groupSelect.style.opacity = '0.5';
                groupSelect.value = ''; // Clear group selection
            } else if (selectedType === 'GROUP') {
                groupSelect.disabled = false;
                groupSelect.style.opacity = '1';
                userSelect.disabled = true;
                userSelect.style.opacity = '0.5';
                userSelect.value = ''; // Clear user selection
            }
        }
    }
    
    // Initialize all actor dropdowns on page load
    <?php for ($i 1$i <= $numStates$i++): ?>
    toggleActorDropdowns(<?= $i ?>);
    
    // Add event listener for actor type changes
    const actorTypeSelect<?= $i ?> = document.querySelector('select[name="actorType_<?= $i ?>"]');
    if (actorTypeSelect<?= $i ?>) {
        actorTypeSelect<?= $i ?>.addEventListener('change', function() {
            toggleActorDropdowns(<?= $i ?>);
        });
    }
    <?php endfor; ?>
});
</script>
</div>