<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="Styles/styles.css">
</head>
<body>
    <?php

        $LINK 
mysqli_connect('127.0.0.1','pisjo950','vjPRjFTxDVIoG7)t','pisjo950');



        
//don't forget the insert also new IN type if new come
        
$selectedWf $_GET['workflow'] ?? null;
        
$fields = [];
        if (
$selectedWf) {
            
$sql "
            SELECT f.id_field, f.label, f.type, f.is_optional
                FROM TicketFields f
                JOIN TicketStates s ON f.fi_steps = s.id_state
            WHERE s.fi_workflow = ?
                AND f.type IN ('text','number','date','select','checkbox')
            ORDER BY s.no, f.id_field
            "
;
            
$stmt $LINK->prepare($sql);
            
$stmt->bind_param('i'$selectedWf);
            
$stmt->execute();
            
$fields $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            
$stmt->close();
        }

        
// 3) If the final form is submitted, handle inserting the ticket
        
if (isset($_POST['submit_ticket'])) {
            
//echo $_SESSION['id'];
            
$wf       = (int)$_POST['workflow_id'];
            
$userName$_SESSION['username'];
            
$userID     $_SESSION['id'];

            
// first insert the request
            
$stmt $LINK->prepare("
            INSERT INTO TicketRequest (fi_workflow, fi_state, iam_inserted,fi_user)
            VALUES (?, (SELECT id_state FROM TicketStates WHERE fi_workflow=? ORDER BY no LIMIT 1), ?,?)"
);
            
$stmt->bind_param('iisi'$wf$wf$userName,$userID);
            
$stmt->execute();
            
$reqId $stmt->insert_id;
            
$stmt->close();
            
// then each dynamic field
            
$stmt $LINK->prepare("
            INSERT INTO TicketData (fi_request, fi_field, value)
            VALUES (?, ?, ?)
            "
);
            foreach (
$fields as $f) {
                
$val $_POST['field_'.$f['id_field']] ?? null;
                
$stmt->bind_param('iis'$reqId$f['id_field'], $val);
                
$stmt->execute();
            }
            
$stmt->close();
            echo 
"<p>Ticket #{$reqId} created!</p>";
            
            
//Also update the TicketState
            // 2) Record the initial state in TicketHasState
            //    We re-use the same sub-select to get the id_state again,
            //    or you can cache it in PHP from the INSERT above.
            
$initStateSql "
            SELECT id_state 
                FROM TicketStates 
            WHERE fi_workflow=? 
            ORDER BY no 
            LIMIT 1
            "
;
            
$st $LINK->prepare($initStateSql);
            
$st->bind_param('i'$wf);
            
$st->execute();
            
$st->bind_result($initialState);
            
$st->fetch();
            
$st->close();

            
$hist $LINK->prepare("
            INSERT INTO TicketHasState
                (fi_request, fi_state, iam_inserted)
            VALUES
                (?, ?, ?)
            "
);
            
$hist->bind_param('iis'$reqId$initialState$userName);
            
$hist->execute();
            
$hist->close();

            
// clear selection so you can start over
            
$selectedWf null;
            
$fields = [];
        }

        
//get all the extratimes
        
$statement $LINK->prepare("SELECT id_workflow,title FROM TicketWorkflows");
        
$statement->execute();
        
$workflows $statement->get_result()->fetch_all(MYSQLI_ASSOC);
        
$statement->close();

        
        if(isset(
$_POST['submit']))
        {
            
$name $_POST['name'];
            
$defaultTime $_POST['defaultTime'];
        
            
//insert into CineEntry
            
$statement $LINK->prepare("INSERT INTO CineExtra(name, defaultTime) VALUES (?, ?)");
            
$statement->bind_param('si'$name$defaultTime);
            
$statement->execute();
            
$statement->close();


            echo 
"New Extra created successfully";
            
header("Location: index.php"); //put this onto the index page instead of loading a new page
        
}
        
    
?>

    <!-- Submit a ticket with dropdown of all workflows -->
     <!-- depending on workflow, show different fields, fields are determined in TicketFields db -->
    <h1>New Ticket</h1>

    <!-- Step 1: choose your workflow -->
    <form method="GET" id="wfForm" action="index.php?page=workflow">
        <input type="hidden" name="page" value="workflow">
        <label for="workflow">Workflow:</label>
        <select name="workflow" id="workflow"
                onchange="document.getElementById('wfForm').submit()">
        <option value="">— Select —</option>
        <?php foreach($workflows as $wf): ?>
            <option
            value="<?= $wf['id_workflow']?>"
            <?= $wf['id_workflow']==$selectedWf'selected':''?>>
            <?= htmlspecialchars($wf['title'])?>
            </option>
        <?php endforeach; ?>
        </select>
    </form>

    <?php if ($selectedWf && $fields): ?>
    <!-- Step 2: render the form for the chosen workflow -->
    <form method="POST">
      <input type="hidden" name="workflow_id" value="<?= $selectedWf ?>">
      <?php foreach ($fields as $f): ?>
        <div class="form-row">
          <label for="field_<?= $f['id_field'?>">
            <?= htmlspecialchars($f['label']) ?>
            <?= $f['is_optional'] ? '' '<span>*</span>' ?>
          </label>

          <?php if ($f['type']==='text'): ?>
            <input type="text"
                   id="field_<?= $f['id_field'?>"
                   name="field_<?= $f['id_field'?>"
                   <?= $f['is_optional'] ? '' 'required' ?>>

          <?php elseif ($f['type']==='number'): ?>
            <input type="number"
                   id="field_<?= $f['id_field'?>"
                   name="field_<?= $f['id_field'?>"
                   <?= $f['is_optional'] ? '' 'required' ?>>

          <?php elseif ($f['type']==='date'): ?>
            <input type="date"
                   id="field_<?= $f['id_field'?>"
                   name="field_<?= $f['id_field'?>"
                   <?= $f['is_optional'] ? '' 'required' ?>>
          <?php elseif($f['type']==='checkbox'): ?>
            <input type="checkbox"
                    id="field_<?= $f['id_field'?>"
                    name="field_<?= $f['id_field'?>"
                    <?= $f['is_optional'] ? '' 'required' ?>>

          <?php elseif ($f['type']==='select'): ?>
            <!-- assumes you have a TicketFieldOptions table -->
            <?php
            $optStmt 
$LINK->prepare("
              SELECT option_value, option_label
              FROM TicketFieldOptions
              WHERE fi_field = ?
            "
);
            
$optStmt->bind_param('i'$f['id_field']);
            
$optStmt->execute();
            
$opts $optStmt->get_result()->fetch_all(MYSQLI_ASSOC);
            
$optStmt->close();
            
?>
            <select id="field_<?= $f['id_field'?>"
                    name="field_<?= $f['id_field'?>"
                    <?= $f['is_optional'] ? '' 'required' ?>>
              <option value="">— choose —</option>
              <?php foreach ($opts as $o): ?>
                <option value="<?= htmlspecialchars($o['option_value'])?>">
                  <?= htmlspecialchars($o['option_label'])?>
                </option>
              <?php endforeach; ?>
            </select>

          <?php endif; ?>
        </div>
      <?php endforeach; ?>

      <button type="submit" name="submit_ticket">Submit Ticket</button>
    </form>
  <?php elseif ($selectedWf): ?>
    <p>No fields defined for this workflow.</p>
  <?php endif; ?>
  <p><a href="index.php">Back</a></p>
</body>
</html>