<?php
require_admin
();

// Handle workflow deletion
if (isset($_POST['delete_workflow'])) {
    
$workflowId = (int)$_POST['workflow_id'];
    
    
// Check if there are any requests for this workflow
    
$checkSql = "SELECT COUNT(*) as request_count FROM TICKET_Request WHERE fk_Workflow = ?";
    
$checkStmt = mysqli_prepare($conn, $checkSql);
    
mysqli_stmt_bind_param($checkStmt, 'i', $workflowId);
    
mysqli_stmt_execute($checkStmt);
    
$checkResult = mysqli_stmt_get_result($checkStmt);
    
$checkRow = mysqli_fetch_assoc($checkResult);
    
    if (
$checkRow['request_count'] > 0) {
        
$error_message = "Cannot delete workflow. There are " . $checkRow['request_count'] . " request(s) associated with this workflow.";
    } else {
        
// Start transaction
        
mysqli_autocommit($conn, false);
        
        try {
            
// Delete workflow-related data in correct order (foreign key constraints)
            
            // Delete state actors
            
$deleteActorsSql = "DELETE sa FROM TICKET_StateActor sa 
                               JOIN TICKET_State s ON sa.fk_State = s.pk_State 
                               WHERE s.fk_Workflow = ?"
;
            
$deleteActorsStmt = mysqli_prepare($conn, $deleteActorsSql);
            
mysqli_stmt_bind_param($deleteActorsStmt, 'i', $workflowId);
            
mysqli_stmt_execute($deleteActorsStmt);
            
            
// Delete fields
            
$deleteFieldsSql = "DELETE f FROM TICKET_Field f 
                               JOIN TICKET_State s ON f.fk_State = s.pk_State 
                               WHERE s.fk_Workflow = ?"
;
            
$deleteFieldsStmt = mysqli_prepare($conn, $deleteFieldsSql);
            
mysqli_stmt_bind_param($deleteFieldsStmt, 'i', $workflowId);
            
mysqli_stmt_execute($deleteFieldsStmt);
            
            
// Delete states
            
$deleteStatesSql = "DELETE FROM TICKET_State WHERE fk_Workflow = ?";
            
$deleteStatesStmt = mysqli_prepare($conn, $deleteStatesSql);
            
mysqli_stmt_bind_param($deleteStatesStmt, 'i', $workflowId);
            
mysqli_stmt_execute($deleteStatesStmt);
            
            
// Finally delete the workflow
            
$deleteWorkflowSql = "DELETE FROM TICKET_Workflow WHERE pk_Workflow = ?";
            
$deleteWorkflowStmt = mysqli_prepare($conn, $deleteWorkflowSql);
            
mysqli_stmt_bind_param($deleteWorkflowStmt, 'i', $workflowId);
            
mysqli_stmt_execute($deleteWorkflowStmt);
            
            
// Commit transaction
            
mysqli_commit($conn);
            
mysqli_autocommit($conn, true);
            
            
$success_message = "Workflow has been deleted successfully.";
        } catch (
Exception $e) {
            
// Rollback transaction
            
mysqli_rollback($conn);
            
mysqli_autocommit($conn, true);
            
$error_message = "Error deleting workflow. Please try again.";
        }
    }
}

$sql = "
  SELECT 
    w.pk_Workflow,
    w.title,
    u.firstName,
    u.lastName,
    (SELECT COUNT(*) FROM TICKET_Request r WHERE r.fk_Workflow = w.pk_Workflow) as request_count
  FROM TICKET_Workflow w
  JOIN TICKET_User     u ON w.iam_inserted = u.pk_User
  ORDER BY w.date_inserted DESC
"
;
$result = mysqli_query($conn, $sql);
$hasWorkflows = mysqli_num_rows($result) > 0;
?>
<div class="page-workflows">
  <div class="page-header">
    <h1 class="page-title">Workflows</h1>
    <a href="index.php?page=workflows_create" class="btn btn-primary">Create New Workflow</a>
  </div>
  
  <?php if (isset($success_message)): ?>
    <div class="alert alert-success">
      <?= htmlspecialchars($success_message) ?>
    </div>
  <?php endif; ?>
  
  <?php if (isset($error_message)): ?>
    <div class="alert alert-error">
      <?= htmlspecialchars($error_message) ?>
    </div>
  <?php endif; ?>
  
  <?php if ($hasWorkflows): ?>
    <div class="workflows-table-container">
      <table class="workflows-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>Title</th>
            <th>Created By</th>
            <th>Requests</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php while ($r = mysqli_fetch_assoc($result)): ?>
            <tr>
              <td>
                <span class="workflow-id"><?= $r['pk_Workflow']; ?></span>
              </td>
              <td>
                <span class="workflow-title"><?= htmlspecialchars($r['title']); ?></span>
              </td>
              <td>
                <span class="creator-name"><?= htmlspecialchars($r['firstName'] . ' ' . $r['lastName']); ?></span>
              </td>
              <td>
                <span class="request-count"><?= $r['request_count'] ?></span>
              </td>
              <td>
                <div class="action-buttons">
                  <a href="index.php?page=workflows_edit&wf=<?= $r['pk_Workflow'] ?>" class="action-button edit-button">
                    Edit
                  </a>
                  <?php if ($r['request_count'] == 0): ?>
                    <button type="button" class="action-button delete-button" onclick="confirmDeleteWorkflow(<?= $r['pk_Workflow'] ?>, '<?= htmlspecialchars($r['title'], ENT_QUOTES) ?>')">
                      Delete
                    </button>
                  <?php else: ?>
                    <button type="button" class="action-button delete-button disabled" title="Cannot delete: <?= $r['request_count'] ?> request(s) exist" disabled>
                      Delete
                    </button>
                  <?php endif; ?>
                </div>
              </td>
            </tr>
          <?php endwhile; ?>
        </tbody>
      </table>
    </div>
  <?php else: ?>
    <div class="workflows-table-container">
      <div style="text-align: center; padding: 3rem 1rem; color: var(--text-secondary);">
        <div style="font-size: 3rem; margin-bottom: 1rem; opacity: 0.5;">⚙️</div>
        <h3 style="font-size: 1.25rem; font-weight: 600; color: var(--text-primary); margin-bottom: 0.5rem;">No Workflows Yet</h3>
        <p style="margin-bottom: 1.5rem;">Create your first workflow to get started with the ticket system.</p>
        <a href="index.php?page=workflows_create" class="btn btn-primary">Create Your First Workflow</a>
      </div>
    </div>
  <?php endif; ?>
</div>

<!-- Hidden form for deletion -->
<form id="deleteWorkflowForm" method="POST" style="display: none;">
  <input type="hidden" name="delete_workflow" value="1">
  <input type="hidden" name="workflow_id" id="deleteWorkflowId">
</form>

<script>
function confirmDeleteWorkflow(workflowId, workflowTitle) {
  if (confirm('Are you sure you want to delete the workflow "' + workflowTitle + '"? This action cannot be undone.')) {
    document.getElementById('deleteWorkflowId').value = workflowId;
    document.getElementById('deleteWorkflowForm').submit();
  }
}
</script>