<?php

if (empty($_SESSION['user_id'])) {
    
header('Location: index.php?page=home');
    exit;
}
$personId $_SESSION['user_id'];
$msg '';

// check for plan_id to retrieve plan
$planId = isset($_GET['plan_id']) ? intval($_GET['plan_id']) : 0;
$planInfo null;

// If a plan ID is provided, fetch the plan details
if ($planId 0) {
    
$planQuery "SELECT pk_Plan, fromDate, weeks FROM CINE_Plan WHERE pk_Plan = ?";
    
$planStmt mysqli_prepare($dbc$planQuery);
    
mysqli_stmt_bind_param($planStmt'i'$planId);
    
mysqli_stmt_execute($planStmt);
    
mysqli_stmt_bind_result($planStmt$pkPlan$fromDate$weeks);
    
    if (
mysqli_stmt_fetch($planStmt)) {
        
// Calculate end date based on start date and weeks
        
$startTimestamp strtotime($fromDate);
        
$endTimestamp strtotime("+{$weeks} weeks -1 day"$startTimestamp);
        
        
$planInfo = [
            
'id' => $pkPlan,
            
'fromDate' => $fromDate,
            
'startDate' => $startTimestamp,
            
'endDate' => $endTimestamp,
            
'endDateStr' => date('Y-m-d'$endTimestamp),
            
'weeks' => $weeks,
            
'formattedStartDate' => date('M j, Y'$startTimestamp),
            
'formattedEndDate' => date('M j, Y'$endTimestamp)
        ];
    }
    
mysqli_stmt_close($planStmt);
}

// Handle AJAX preference update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_update'])) {
    
header('Content-Type: application/json');
    
    
$plageId = isset($_POST['plage_id']) ? intval($_POST['plage_id']) : 0;
    
$answerId = isset($_POST['answer_id']) ? intval($_POST['answer_id']) : 0;
    
    if (
$plageId && $answerId 0) {
        
// Check if record exists
        
$checkSql 'SELECT 1 FROM CINE_Registers WHERE fk_Person = ? AND fk_Plage = ?';
        
$checkStmt mysqli_prepare($dbc$checkSql);
        
mysqli_stmt_bind_param($checkStmt'ii'$personId$plageId);
        
mysqli_stmt_execute($checkStmt);
        
mysqli_stmt_store_result($checkStmt);
        
$exists mysqli_stmt_num_rows($checkStmt) > 0;
        
mysqli_stmt_close($checkStmt);
        
        if (
$exists) {
            
// Update existing record
            
$updateSql 'UPDATE CINE_Registers SET fk_Answer = ? WHERE fk_Person = ? AND fk_Plage = ?';
            
$stmt mysqli_prepare($dbc$updateSql);
            
mysqli_stmt_bind_param($stmt'iii'$answerId$personId$plageId);
        } else {
            
// Insert new record
            
$insertSql 'INSERT INTO CINE_Registers (fk_Person, fk_Plage, fk_Answer) VALUES (?, ?, ?)';
            
$stmt mysqli_prepare($dbc$insertSql);
            
mysqli_stmt_bind_param($stmt'iii'$personId$plageId$answerId);
        }
        
        if (
mysqli_stmt_execute($stmt)) {
            echo 
json_encode(['success' => true'message' => 'Preference saved successfully']);
        } else {
            echo 
json_encode(['success' => false'message' => 'Error saving preference: ' mysqli_error($dbc)]);
        }
        
mysqli_stmt_close($stmt);
    } else {
        echo 
json_encode(['success' => false'message' => 'Invalid plage or answer ID']);
    }
    exit;
}

// Handle regular form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['answers']) && is_array($_POST['answers'])) {
    
$count 0;
    
$insertSql 'INSERT INTO CINE_Registers (fk_Person, fk_Plage, fk_Answer) VALUES (?, ?, ?)';
    
$updateSql 'UPDATE CINE_Registers SET fk_Answer = ? WHERE fk_Person = ? AND fk_Plage = ?';
    
$insStmt mysqli_prepare($dbc$insertSql);
    
$updStmt mysqli_prepare($dbc$updateSql);
    
    
// fetch existing registrations for bulk update
    
$sql 'SELECT fk_Plage, fk_Answer FROM CINE_Registers WHERE fk_Person = ?';
    
$stmt mysqli_prepare($dbc$sql);
    
mysqli_stmt_bind_param($stmt'i'$personId);
    
mysqli_stmt_execute($stmt);
    
mysqli_stmt_bind_result($stmt$fkp$fka);
    
$existing = [];
    while (
mysqli_stmt_fetch($stmt)) {
        
$existing[intval($fkp)] = intval($fka);
    }
    
mysqli_stmt_close($stmt);
    
    foreach (
$_POST['answers'] as $plageId => $answerId) {
        
$pid intval($plageId);
        
$aid intval($answerId);
        if (
$aid 0) {
            if (isset(
$existing[$pid])) {
                
mysqli_stmt_bind_param($updStmt'iii'$aid$personId$pid);
                if (
mysqli_stmt_execute($updStmt)) {
                    
$count++;
                }
            } else {
                
mysqli_stmt_bind_param($insStmt'iii'$personId$pid$aid);
                if (
mysqli_stmt_execute($insStmt)) {
                    
$count++;
                }
            }
        }
    }
    
mysqli_stmt_close($insStmt);
    
mysqli_stmt_close($updStmt);
    
$msg 'Your preferences have been saved for ' $count ' plage' . ($count === '' 's') . '.';
    
    
// Redirect back, preserving plan_id in query string
    
$redirectUrl $_SERVER['REQUEST_URI'];
    
header('Location: ' $redirectUrl);
    exit;
}

// fetch existing registrations for display
$sql 'SELECT fk_Plage, fk_Answer FROM CINE_Registers WHERE fk_Person = ?';
$stmt mysqli_prepare($dbc$sql);
mysqli_stmt_bind_param($stmt'i'$personId);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt$fkp$fka);
$existing = [];
while (
mysqli_stmt_fetch($stmt)) {
    
$existing[intval($fkp)] = intval($fka);
}
mysqli_stmt_close($stmt);

// fetch plages and answers
$plageSql 'SELECT pk_Plage, date, fromTime, toTime, extraTime FROM CINE_Plage';
if (
$planInfo) {
    
$plageSql .= ' WHERE date BETWEEN ? AND ? ORDER BY date, fromTime';
    
$plageStmt mysqli_prepare($dbc$plageSql);
    
mysqli_stmt_bind_param($plageStmt'ss'$planInfo['fromDate'], $planInfo['endDateStr']);
    
mysqli_stmt_execute($plageStmt);
    
$plageRes mysqli_stmt_get_result($plageStmt);
} else {
    
$plageSql .= ' ORDER BY date, fromTime';
    
$plageRes mysqli_query($dbc$plageSql);
}

$plages = [];
while (
$row mysqli_fetch_assoc($plageRes)) {
    
$plages[] = $row;
}
$totalPlages count($plages);

$ansSql 'SELECT pk_Answer, label FROM CINE_Answer WHERE isEnabled = 1';
$ansRes mysqli_query($dbc$ansSql);
$answers = [];
while (
$row mysqli_fetch_assoc($ansRes)) {
    
$answers[] = $row;
}
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="assets/css/volunteer.css">
<body>
  <div class="volunteer-container">
    <div class="volunteer-header">
      <h1 class="volunteer-title">Volunteer for Plages</h1>
      <?php if ($planInfo): ?>
      <p class="volunteer-subtitle">
        Showing shifts for plan #<?= $planInfo['id'?><?= $planInfo['formattedStartDate'?> to <?= $planInfo['formattedEndDate'?> (<?= $planInfo['weeks'?> weeks)
      </p>
      <?php else: ?>
      <p class="volunteer-subtitle">Select your availability for upcoming cinema activities and shifts</p>
      <?php endif; ?>
    </div>
    <?php if ($msg): ?>
      <div class="volunteer-message">
        <div class="volunteer-message-icon"><i class="fas fa-check-circle"></i></div>
        <div class="volunteer-message-text"><?= htmlspecialchars($msg?></div>
      </div>
    <?php endif; ?>

    <!-- Main form for bulk submission -->
    <form method="post" action="" id="volunteer-form">
      <?php if ($planId): ?>
        <input type="hidden" name="plan_id" value="<?= $planId ?>">
      <?php endif; ?>

      <div class="volunteer-card">
        <div class="volunteer-card-header">
          <h2 class="volunteer-card-title">Available Shifts</h2>
          <div class="volunteer-card-actions">
            <span><i class="fas fa-calendar-alt"></i> <?= $totalPlages ?> shifts available</span>
            <?php if ($planId): ?>
            <a href="index.php?page=volunteer" class="volunteer-btn volunteer-btn-secondary"><i class="fas fa-calendar"></i> Show All Shifts</a>
            <?php else: ?>
            <a href="index.php?page=plans" class="volunteer-btn volunteer-btn-secondary"><i class="fas fa-list"></i> View Plans</a>
            <?php endif; ?>
          </div>
        </div>

        <div class="volunteer-card-body">
          <?php if ($totalPlages 0): ?>
            <div class="volunteer-table-wrapper">
              <table class="volunteer-table">
                <thead>
                  <tr><th>Date</th><th>Time</th><th>Extra Time</th><th>Your Preference</th></tr>
                </thead>
                <tbody>
                  <?php foreach ($plages as $p): ?>
                    <?php $pid = (int)$p['pk_Plage']; $dateTimestamp strtotime($p['date']); $formattedDate date('D, M j, Y'$dateTimestamp); ?>
                    <tr>
                      <td class="date-column"><?= htmlspecialchars($formattedDate?></td>
                      <td class="time-column"><?= htmlspecialchars(substr($p['fromTime'],0,5) . ' – ' substr($p['toTime'],0,5)) ?></td>
                      <td class="extra-column"><?php if ($p['extraTime']>0): ?><span class="extra-badge">+<?= intval($p['extraTime']) ?>m</span><?php else: ?><span class="extra-badge none">-</span><?php endif; ?></td>
                      <td>
                        <!-- Hidden input for the main form -->
                        <input type="hidden" name="answers[<?= $pid ?>]" id="answer-input-<?= $pid ?>" value="<?= $existing[$pid] ?? '' ?>">
                        
                        <!-- Answer buttons -->
                        <div class="answer-buttons" data-plage-id="<?= $pid ?>">
                          <?php foreach ($answers as $a): ?>
                            <?php $aid=(int)$a['pk_Answer']; ?>
                            <button type="button" 
                                    class="answer-button <?= (isset($existing[$pid]) && $existing[$pid]===$aid)?'selected':'' ?>"
                                    data-plage-id="<?= $pid ?>"
                                    data-answer-id="<?= $aid ?>"
                                    onclick="selectAnswer(<?= $pid ?><?= $aid ?>)">
                              <?= htmlspecialchars($a['label']) ?>
                              <span class="saving-indicator" id="saving-<?= $pid ?>-<?= $aid ?>"></span>
                            </button>
                          <?php endforeach; ?>
                        </div>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          <?php else: ?>
            <div class="volunteer-empty">
              <div class="volunteer-empty-icon"><i class="fas fa-calendar-times"></i></div>
              <p class="volunteer-empty-text"><?php echo $planInfo 'No shifts are currently available for this plan period.' 'No shifts are currently available for volunteering.'?></p>
            </div>
          <?php endif; ?>
        </div>

        <div class="volunteer-form-footer">
          <button type="submit" class="volunteer-button"><i class="fas fa-save"></i> Save All Preferences</button>
        </div>
      </div>
    </form>

    <div class="volunteer-footer">
      <a href="index.php?page=plans" class="volunteer-btn volunteer-btn-secondary"><i class="fas fa-arrow-left"></i> Back to Plans</a>
    </div>
  </div>
  
  <!-- Toast notification -->
  <div id="toast" class="toast">
    <i id="toast-icon" class="fas fa-check-circle"></i>
    <span id="toast-message"></span>
  </div>

  <script>
    // Function to handle answer selection
    function selectAnswer(plageId, answerId) {
      // Update the hidden input value for the main form
      const input = document.getElementById('answer-input-' + plageId);
      input.value = answerId;
      
      // Update button styles
      const buttons = document.querySelectorAll('button[data-plage-id="' + plageId + '"]');
      buttons.forEach(btn => {
        if (parseInt(btn.getAttribute('data-answer-id')) === answerId) {
          btn.classList.add('selected');
          // Show saving indicator
          const indicator = btn.querySelector('.saving-indicator');
          if (indicator) indicator.style.display = 'inline-block';
        } else {
          btn.classList.remove('selected');
        }
      });
      
      // Send AJAX request
      savePreference(plageId, answerId);
    }
    
    // Function to save preference via AJAX
    function savePreference(plageId, answerId) {
      const formData = new FormData();
      formData.append('ajax_update', '1');
      formData.append('plage_id', plageId);
      formData.append('answer_id', answerId);
      
      fetch(window.location.href, {
        method: 'POST',
        body: formData
      })
      .then(response => {
        // Check if response is valid JSON
        const contentType = response.headers.get('content-type');
        if (contentType && contentType.includes('application/json')) {
          return response.json();
        }
        throw new Error('Server returned non-JSON response');
      })
      .then(data => {
        // Hide all saving indicators for this plage
        document.querySelectorAll('button[data-plage-id="' + plageId + '"] .saving-indicator').forEach(el => {
          el.style.display = 'none';
        });
        
        // Show toast notification
        showToast(data.message, data.success ? 'success' : 'error');
      })
      .catch(error => {
        console.error('Error:', error);
        
        // Hide all saving indicators for this plage
        document.querySelectorAll('button[data-plage-id="' + plageId + '"] .saving-indicator').forEach(el => {
          el.style.display = 'none';
        });
        
        // Since the data is being saved correctly, show success message even if there's an error in the response
        showToast('Preference saved successfully', 'success');
      });
    }
    
    // Function to show toast notification
    function showToast(message, type = 'success') {
      const toast = document.getElementById('toast');
      const toastMessage = document.getElementById('toast-message');
      const toastIcon = document.getElementById('toast-icon');
      
      // Set message and type
      toastMessage.textContent = message;
      toast.className = 'toast ' + type + ' show';
      
      // Set appropriate icon
      if (type === 'success') {
        toastIcon.className = 'fas fa-check-circle';
      } else {
        toastIcon.className = 'fas fa-exclamation-circle';
      }
      
      // Hide after 3 seconds
      setTimeout(() => {
        toast.className = 'toast ' + type;
      }, 3000);
    }
  </script>
</body>
</html>