<?php
require_login
();
require_once 
__DIR__ . '/../includes/email_phpmailer_manual.php';

// Get request ID and user/group info
$reqId   = intval($_GET['req']  ?? $_POST['req']  ?? 0);
$userId  = $_SESSION['user_id'];
$groupId = $_SESSION['user_group_id'];

// 1) Load current workflow, state, original creator, and closed flag
$sql = "
  SELECT r.fk_Workflow,
         r.fk_State,
         r.fk_User AS creator_user_id,
         r.is_closed,
         w.title AS workflow_title,
         s.no    AS state_no,
         s.title AS state_title
    FROM TICKET_Request r
    JOIN TICKET_Workflow w ON r.fk_Workflow = w.pk_Workflow
    JOIN TICKET_State    s ON r.fk_State    = s.pk_State
   WHERE r.pk_Request = ?
"
;
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, 'i', $reqId);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result(
  
$stmt,
  
$wfId,
  
$stateId,
  
$creatorUserId,
  
$isClosed,
  
$wfTitle,
  
$stNo,
  
$stTitle
);
if (!
mysqli_stmt_fetch($stmt)) {
  exit(
'Invalid request ID');
}
mysqli_stmt_close($stmt);

// Get requester name for email notifications
$requesterSql = "SELECT firstName, lastName FROM TICKET_User WHERE pk_User = ?";
$requesterStmt = mysqli_prepare($conn, $requesterSql);
mysqli_stmt_bind_param($requesterStmt, 'i', $creatorUserId);
mysqli_stmt_execute($requesterStmt);
mysqli_stmt_bind_result($requesterStmt, $requesterFirstName, $requesterLastName);
mysqli_stmt_fetch($requesterStmt);
mysqli_stmt_close($requesterStmt);
$requesterName = $requesterFirstName . ' ' . $requesterLastName;

// Determine basic flags
$isCreator   = ($userId == $creatorUserId);

// Determine total number of states for this workflow
$countSql = "SELECT COUNT(*) FROM TICKET_State WHERE fk_Workflow = ?";
$countStmt = mysqli_prepare($conn, $countSql);
mysqli_stmt_bind_param($countStmt, 'i', $wfId);
mysqli_stmt_execute($countStmt);
mysqli_stmt_bind_result($countStmt, $totalStates);
mysqli_stmt_fetch($countStmt);
mysqli_stmt_close($countStmt);

$isLastState = ($stNo == $totalStates);

// Determine if the current user can respond to this state
$canRespond = false;
$actorTypeForCurrentState = '';
$actorNameForCurrentState = '';

$authSql = "
  SELECT sa.actorType, u.firstName, u.lastName, g.name AS groupName, sa.fk_User, sa.fk_Group
    FROM TICKET_StateActor sa
    LEFT JOIN TICKET_User u ON sa.fk_User = u.pk_User
    LEFT JOIN TICKET_Group g ON sa.fk_Group = g.pk_Group
   WHERE sa.fk_State = ?
"
;
$aStmt = mysqli_prepare($conn, $authSql);
mysqli_stmt_bind_param($aStmt, 'i', $stateId);
mysqli_stmt_execute($aStmt);
$authResult = mysqli_stmt_get_result($aStmt);

$currentActors = [];
while (
$row = mysqli_fetch_assoc($authResult)) {
    
$currentActors[] = $row;
}
mysqli_free_result($authResult);
mysqli_stmt_close($aStmt);

foreach (
$currentActors as $actor) {
    if (
$actor['actorType'] === 'USER' && $actor['fk_User'] == $userId) {
        
$canRespond = true;
        
$actorTypeForCurrentState = 'USER';
        
$actorNameForCurrentState = htmlspecialchars($actor['firstName'] . ' ' . $actor['lastName']);
        break;
    } elseif (
$actor['actorType'] === 'GROUP' && $actor['fk_Group'] == $groupId) {
        
$canRespond = true;
        
$actorTypeForCurrentState = 'GROUP';
        
$actorNameForCurrentState = htmlspecialchars($actor['groupName']);
        break;
    }
}
if (!
$canRespond && !empty($currentActors)) {
    
$firstActor = $currentActors[0];
    
$actorTypeForCurrentState = $firstActor['actorType'];
    
$actorNameForCurrentState =
        
$firstActor['actorType'] === 'USER'
        
? htmlspecialchars($firstActor['firstName'] . ' ' . $firstActor['lastName'])
        : 
htmlspecialchars($firstActor['groupName']);
}

// Handle POST: save data and advance/close
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $canRespond) {
    
// Save responses
    
foreach ($_POST as $k => $v) {
        if (
strpos($k, 'field_') === 0) {
            
$fid = intval(substr($k, 6));
            
$val = is_array($v) ? '1' : trim($v);
            
$ds = mysqli_prepare(
                
$conn,
                
'INSERT INTO TICKET_Data (fk_Request, fk_Field, value) VALUES (?, ?, ?)'
            
);
            
mysqli_stmt_bind_param($ds, 'iis', $reqId, $fid, $val);
            
mysqli_stmt_execute($ds);
            
mysqli_stmt_close($ds);
        }
    }

    if (!
$isLastState) {
        
// Advance to next state
        
$nSql = "
          SELECT pk_State, title
            FROM TICKET_State
           WHERE fk_Workflow = ?
        ORDER BY `no` ASC
           LIMIT 1 OFFSET ?
        "
;
        
$nStmt = mysqli_prepare($conn, $nSql);
        
mysqli_stmt_bind_param($nStmt, 'ii', $wfId, $stNo);
        
mysqli_stmt_execute($nStmt);
        
$nRes = mysqli_stmt_get_result($nStmt);

        if (
$nRow = mysqli_fetch_assoc($nRes)) {
            
$nextState = $nRow['pk_State'];
            
$nextStateTitle = $nRow['title'];

            
$upd = mysqli_prepare(
                
$conn,
                
'UPDATE TICKET_Request SET fk_State = ? WHERE pk_Request = ?'
            
);
            
mysqli_stmt_bind_param($upd, 'ii', $nextState, $reqId);
            
mysqli_stmt_execute($upd);
            
mysqli_stmt_close($upd);

            
$hs = mysqli_prepare(
                
$conn,
                
'INSERT INTO TICKET_hasState (fk_Request, fk_State, iam_inserted) VALUES (?, ?, ?)'
            
);
            
mysqli_stmt_bind_param($hs, 'iii', $reqId, $nextState, $userId);
            
mysqli_stmt_execute($hs);
            
mysqli_stmt_close($hs);

            
// Create notifications for the next state's actors
            
$actorSql = "
                SELECT sa.actorType, sa.fk_User, sa.fk_Group
                FROM TICKET_StateActor sa
                WHERE sa.fk_State = ?
            "
;
            
$actorStmt = mysqli_prepare($conn, $actorSql);
            if (
$actorStmt) {
                
mysqli_stmt_bind_param($actorStmt, 'i', $nextState);
                
mysqli_stmt_execute($actorStmt);
                
$actorResult = mysqli_stmt_get_result($actorStmt);
                
                while (
$actor = mysqli_fetch_assoc($actorResult)) {
                    if (
$actor['actorType'] === 'USER' && $actor['fk_User']) {
                        
// Direct user notification
                        
$notifStmt = mysqli_prepare($conn, 
                            
'INSERT INTO TICKET_Notifications (fk_State, fk_User, fk_Request) VALUES (?, ?, ?)'
                        
);
                        
mysqli_stmt_bind_param($notifStmt, 'iii', $nextState, $actor['fk_User'], $reqId);
                        
mysqli_stmt_execute($notifStmt);
                        
mysqli_stmt_close($notifStmt);
                        
                    } elseif (
$actor['actorType'] === 'GROUP' && $actor['fk_Group']) {
                        
// Group notification - notify all users in the group
                        
$groupUsersSql = "SELECT pk_User FROM TICKET_User WHERE fk_Group = ?";
                        
$groupUsersStmt = mysqli_prepare($conn, $groupUsersSql);
                        
mysqli_stmt_bind_param($groupUsersStmt, 'i', $actor['fk_Group']);
                        
mysqli_stmt_execute($groupUsersStmt);
                        
$groupUsersResult = mysqli_stmt_get_result($groupUsersStmt);
                        
                        while (
$groupUser = mysqli_fetch_assoc($groupUsersResult)) {
                            
$notifStmt = mysqli_prepare($conn, 
                                
'INSERT INTO TICKET_Notifications (fk_State, fk_User, fk_Request) VALUES (?, ?, ?)'
                            
);
                            
mysqli_stmt_bind_param($notifStmt, 'iii', $nextState, $groupUser['pk_User'], $reqId);
                            
mysqli_stmt_execute($notifStmt);
                            
mysqli_stmt_close($notifStmt);
                        }
                        
mysqli_stmt_close($groupUsersStmt);
                    }
                }
                
mysqli_stmt_close($actorStmt);
            }

            
// Send email notifications to next state actors using PHPMailer
            
send_actor_notification_emails_phpmailer($conn, $nextState, $reqId, $wfTitle, $nextStateTitle, $requesterName);
        }
        
mysqli_free_result($nRes);
        
mysqli_stmt_close($nStmt);

        
header("Location: index.php?page=request_handle&req={$reqId}");
        exit;

    } else {
        
// Final step completed: mark closed
        
$closeStmt = mysqli_prepare($conn, 'UPDATE TICKET_Request SET is_closed = 1 WHERE pk_Request = ?');
        
mysqli_stmt_bind_param($closeStmt, 'i', $reqId);
        
mysqli_stmt_execute($closeStmt);
        
mysqli_stmt_close($closeStmt);

        
// Create completion notification for the original requester
        
$completionNotifStmt = mysqli_prepare($conn, 
            
'INSERT INTO TICKET_Notifications (fk_State, fk_User, fk_Request) VALUES (?, ?, ?)'
        
);
        
mysqli_stmt_bind_param($completionNotifStmt, 'iii', $stateId, $creatorUserId, $reqId);
        
mysqli_stmt_execute($completionNotifStmt);
        
mysqli_stmt_close($completionNotifStmt);

        
// Send completion email to requester using PHPMailer
        
send_completion_notification_email_phpmailer($conn, $reqId, $wfTitle, $stTitle, $creatorUserId);

        
header("Location: index.php?page=request_handle&req={$reqId}&done=1");
        exit;
    }
}

// Check if just completed this session
$justCompleted = (isset($_GET['done']) && $_GET['done'] == 1);
?>

<div class="page-request-handle">
  <div class="page-header">
    <h1 class="page-title"><?= htmlspecialchars($wfTitle) ?></h1>
    <p class="page-subtitle">
      Current State: <?= htmlspecialchars($stTitle) ?>
      <span class="stage-indicator">Stage <?= $stNo ?> of <?= $totalStates ?></span>
    </p>
  </div>

  <div class="data-section">
    <h3 class="section-title">📋 Collected Data</h3>
    <?php
    
// Fetch all data grouped by state
    
$dataSql = "
      SELECT s.no AS state_no,
             s.title AS state_title,
             tf.label AS field_label,
             td.value AS field_value
        FROM TICKET_Data td
        JOIN TICKET_Field tf ON td.fk_Field = tf.id_field
        JOIN TICKET_State s ON tf.fk_State = s.pk_State
       WHERE td.fk_Request = ?
       ORDER BY s.no ASC, tf.id_field ASC
    "
;
    
$dataStmt = mysqli_prepare($conn, $dataSql);
    
mysqli_stmt_bind_param($dataStmt, 'i', $reqId);
    
mysqli_stmt_execute($dataStmt);
    
$res = mysqli_stmt_get_result($dataStmt);

    
$byStage = [];
    while (
$row = mysqli_fetch_assoc($res)) {
      
$sn = $row['state_no'];
      if (!isset(
$byStage[$sn])) {
        
$byStage[$sn] = [
          
'title'  => $row['state_title'],
          
'fields' => []
        ];
      }
      
$byStage[$sn]['fields'][] = [
        
'label' => $row['field_label'],
        
'value' => $row['field_value'],
      ];
    }
    
mysqli_free_result($res);
    
mysqli_stmt_close($dataStmt);
    
?>

    <?php if (empty($byStage)): ?>
      <p class="no-data-message">No data collected for this request yet.</p>
    <?php else: ?>
      <?php foreach ($byStage as $stageNo => $stage): ?>
        <div class="state-responses">
          <h4 class="section-title">Stage <?= $stageNo ?>: <?= htmlspecialchars($stage['title']) ?></h4>
          <table class="data-table">
            <thead>
              <tr><th>Field</th><th>Value</th></tr>
            </thead>
            <tbody>
              <?php foreach ($stage['fields'] as $f): ?>
                <tr>
                  <td><?= htmlspecialchars($f['label']) ?></td>
                  <td><?= htmlspecialchars($f['value']) ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>

  <?php if ($isClosed || $justCompleted): ?>
    <div class="status-message completed">
      <span>✅</span>
      <div>
        <strong>Request Completed</strong>
        <p>This request has been closed and can no longer be modified, but you can still view the collected data above.</p>
      </div>
    </div>

  <?php elseif ($canRespond): ?>
    <div class="response-section">
      <h3 class="section-title"><?= $isLastState ? '✏️ Final Response' : '✏️ Respond to this stage' ?></h3>
      <?php
      $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);
      
?>
      <form method="post" action="index.php?page=request_handle" class="response-form">
        <input type="hidden" name="req" value="<?= $reqId ?>">
        <?php while ($field = mysqli_fetch_assoc($fRes)):
          
$fname = "field_{$field['id_field']}";
        
?>
          <div class="field-group">
            <label class="field-label"><?= htmlspecialchars($field['label']) ?><?php if (!$field['is_optional']): ?> <span class="required-indicator">*</span><?php endif; ?></label>
            <?php if ($field['type'] === 'input' || $field['type'] === 'text'): ?>
              <input type="text" name="<?= $fname ?>" class="field-input" <?= $field['is_optional'] ? '' : 'required' ?>>
            <?php elseif ($field['type'] === 'date'): ?>
              <input type="date" name="<?= $fname ?>" class="field-input" <?= $field['is_optional'] ? '' : 'required' ?>>
            <?php elseif ($field['type'] === 'number'): ?>
              <input type="number" name="<?= $fname ?>" class="field-input" <?= $field['is_optional'] ? '' : 'required' ?>>
            <?php elseif ($field['type'] === 'checkbox'): ?>
              <div class="checkbox-group">
                <input type="checkbox" name="<?= $fname ?>" id="<?= $fname ?>" class="checkbox-input">
                <label for="<?= $fname ?>">Yes</label>
              </div>
            <?php endif; ?>
          </div>
        <?php endwhile; mysqli_free_result($fRes); mysqli_stmt_close($fStmt); ?>
        <button type="submit" class="submit-button"><?= $isLastState ? 'Submit Final Response & Close' : 'Submit Response & Advance' ?></button>
      </form>
    </div>

  <?php elseif ($isCreator): ?>
    <div class="status-message waiting">
      <span>⏳</span>
      <div>
        <strong>Waiting for Response</strong>
        <p>You are the creator of this request. It is currently awaiting response from <?= $actorNameForCurrentState ?> (<?= $actorTypeForCurrentState ?>).</p>
      </div>
    </div>

  <?php else: ?>
    <div class="status-message unauthorized">
      <span>🚫</span>
      <div>
        <strong>Access Denied</strong>
        <p>You are not authorized to view or respond to this request at its current stage.</p>
      </div>
    </div>
  <?php endif; ?>
</div>