<?php
// participants_update.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
require_login();

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$id) {
    echo "Invalid participant ID.";
    exit;
}


$sql = "
SELECT p.*, 
  d.name AS district_name, b.name AS block_name, g.name AS gp_name, s.name AS school_name
FROM participants p
LEFT JOIN districts d ON d.id=p.district_id
LEFT JOIN blocks b ON b.id=p.block_id
LEFT JOIN gps g ON g.id=p.gp_id
LEFT JOIN schools s ON s.id=p.school_id
WHERE p.id = ?
";
$stmt = $pdo->prepare($sql);
$stmt->execute([$id]);
$participant = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$participant) {
    echo "Participant not found.";
    exit;
}


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $full_name = trim($_POST['full_name'] ?? '');
  $gender = trim($_POST['gender'] ?? '');
  $age = (int)($_POST['age'] ?? 0);
  $district_id = trim($_POST['district_id'] ?? '');
  $block_id = trim($_POST['block_id'] ?? '');
  $gp_id = trim($_POST['gp_id'] ?? '');
  $school_id = trim($_POST['school_id'] ?? '');
  $guardian_name = trim($_POST['guardian_name'] ?? '');
  $guardian_phone = trim($_POST['guardian_phone'] ?? '');
  $whatsapp = trim($_POST['whatsapp'] ?? '');
  $optional_phone = trim($_POST['optional_phone'] ?? '');
  $address = trim($_POST['address'] ?? '');
  $dance_type = trim($_POST['dance_type'] ?? '');
  $notes = trim($_POST['notes'] ?? '');
  // Category is not editable, use from DB
  $category = $participant['category'];

  $stmt = $pdo->prepare('UPDATE participants SET full_name=?, gender=?, age=?, district_id=?, block_id=?, gp_id=?, school_id=?, guardian_name=?, guardian_phone=?, whatsapp=?, optional_phone=?, address=?, dance_type=?, notes=? WHERE id=?');
  $stmt->execute([$full_name, $gender, $age, $district_id, $block_id, $gp_id, $school_id, $guardian_name, $guardian_phone, $whatsapp, $optional_phone, $address, $dance_type, $notes, $id]);

  // Update group members if GROUP
  if ($category === 'GROUP') {
    // Remove old members
    $pdo->prepare('DELETE FROM group_members WHERE participant_id=?')->execute([$id]);
    // Insert new/updated members
    if (isset($_POST['members']) && is_array($_POST['members'])) {
      $stmt = $pdo->prepare('INSERT INTO group_members (participant_id, name, age, gender, guardian_name, guardian_phone, address) VALUES (?, ?, ?, ?, ?, ?, ?)');
      foreach ($_POST['members'] as $member) {
        $stmt->execute([
          $id,
          trim($member['name'] ?? ''),
          (int)($member['age'] ?? 0),
          trim($member['gender'] ?? ''),
          trim($member['guardian_name'] ?? ''),
          trim($member['guardian_phone'] ?? ''),
          trim($member['address'] ?? ''),
        ]);
      }
    }
  }
  header('Location: participants.php');
  exit;
}

$page_title = "Update Participant";
require_once __DIR__ . "/partials/header.php";
?>
<div class="container py-4">
  <h4>Update Participant</h4>
  <form method="post" id="update-form">
    <div class="row">
      <div class="col-md-6 mb-3">
        <label class="form-label">Full Name</label>
        <input type="text" name="full_name" class="form-control" value="<?= htmlspecialchars($participant['full_name']) ?>" required maxlength="120">
      </div>
      <div class="col-md-3 mb-3">
        <label class="form-label">Age (5-21 years)</label>
        <input type="number" name="age" class="form-control" value="<?= htmlspecialchars($participant['age']) ?>" min="5" max="21" required>
      </div>
      <div class="col-md-3 mb-3">
        <label class="form-label">Gender</label>
        <select name="gender" class="form-select" required>
          <option value="">Select Gender</option>
          <option value="MALE" <?= $participant['gender']==='MALE'?'selected':'' ?>>Male</option>
          <option value="FEMALE" <?= $participant['gender']==='FEMALE'?'selected':'' ?>>Female</option>
          <option value="OTHER" <?= $participant['gender']==='OTHER'?'selected':'' ?>>Other</option>
        </select>
      </div>
    </div>
    <div class="row">
      <div class="col-md-6 mb-3">
        <label class="form-label">Guardian Name</label>
        <input type="text" name="guardian_name" class="form-control" value="<?= htmlspecialchars($participant['guardian_name']) ?>" required maxlength="120">
      </div>
      <div class="col-md-4 mb-3">
        <label class="form-label">Guardian Phone</label>
        <input type="tel" name="guardian_phone" id="update-guardian_phone" class="form-control" value="<?= htmlspecialchars($participant['guardian_phone']) ?>" required maxlength="50">
      </div>
      <div class="col-md-4 mb-3">
        <label class="form-label">WhatsApp Number</label>
        <div class="input-group">
          <input type="tel" name="whatsapp" id="update-whatsapp" class="form-control" value="<?= htmlspecialchars($participant['whatsapp'] ?? '') ?>" maxlength="50">
          <button type="button" class="btn btn-outline-secondary" onclick="document.getElementById('update-whatsapp').value = document.getElementById('update-guardian_phone').value">Same as Phone</button>
        </div>
        <div class="form-text">Optional. Click button to copy phone number.</div>
      </div>
      <div class="col-md-4 mb-3">
        <label class="form-label">Optional Phone Number</label>
        <input type="tel" name="optional_phone" class="form-control" value="<?= htmlspecialchars($participant['optional_phone'] ?? '') ?>" maxlength="50">
      </div>
    </div>
    <div class="mb-3">
      <label class="form-label">Address</label>
      <textarea name="address" class="form-control" rows="2" required maxlength="255"><?= htmlspecialchars($participant['address'] ?? '') ?></textarea>
    </div>
    <div class="row">
      <div class="col-md-3 mb-3">
        <label class="form-label">District</label>
        <select name="district_id" id="update-district" class="form-select" required>
          <option value="">Select District</option>
          <?php $dists = $pdo->query('SELECT id, name FROM districts ORDER BY name')->fetchAll();
          foreach ($dists as $dist) {
            $sel = $participant['district_id']==$dist['id']?'selected':'';
            echo "<option value='".htmlspecialchars($dist['id'])."' $sel>".htmlspecialchars($dist['name'])."</option>";
          } ?>
        </select>
      </div>
      <div class="col-md-3 mb-3">
        <label class="form-label">Block</label>
        <select name="block_id" id="update-block" class="form-select" required>
          <option value="">Select Block</option>
        </select>
      </div>
      <div class="col-md-3 mb-3">
        <label class="form-label">Gram Panchayat</label>
        <select name="gp_id" id="update-gp" class="form-select" required>
          <option value="">Select GP</option>
        </select>
      </div>
      <div class="col-md-3 mb-3">
        <label class="form-label">School</label>
        <select name="school_id" id="update-school" class="form-select" required>
          <option value="">Select School</option>
        </select>
      </div>
    </div>
    <div class="row">
      <div class="col-md-6 mb-3">
        <label class="form-label">Dance Type</label>
        <input type="text" name="dance_type" class="form-control" value="<?= htmlspecialchars($participant['dance_type'] ?? '') ?>" maxlength="120">
      </div>
      <div class="col-md-6 mb-3">
        <label class="form-label">Additional Notes</label>
        <textarea name="notes" class="form-control" rows="1" maxlength="255"><?= htmlspecialchars($participant['notes'] ?? '') ?></textarea>
      </div>
    </div>
    <?php if ($participant['category'] === 'GROUP'): ?>
    <h5 class="mt-4">Group Members</h5>
    <div id="members-container">
      <?php
      $groupSql = "SELECT * FROM group_members WHERE participant_id = ?";
      $groupStmt = $pdo->prepare($groupSql);
      $groupStmt->execute([$id]);
      $members = $groupStmt->fetchAll(PDO::FETCH_ASSOC);
      if ($members) {
        foreach ($members as $index => $member) {
      ?>
      <div class="member-card card mb-3">
        <div class="card-header bg-light py-2 d-flex justify-content-between align-items-center">
          <span class="fw-bold text-primary">Member <?= $index + 1 ?></span>
          <button type="button" class="btn btn-outline-danger btn-sm remove-member">Remove</button>
        </div>
        <div class="card-body">
          <div class="row">
            <div class="col-md-6 mb-2">
              <label class="form-label">Full Name</label>
              <input type="text" class="form-control form-control-sm" name="members[<?= $index ?>][name]" value="<?= htmlspecialchars($member['name']) ?>" required maxlength="120">
            </div>
            <div class="col-md-3 mb-2">
              <label class="form-label">Age</label>
              <input type="number" class="form-control form-control-sm" name="members[<?= $index ?>][age]" value="<?= htmlspecialchars($member['age']) ?>" min="5" max="21" required>
            </div>
            <div class="col-md-3 mb-2">
              <label class="form-label">Gender</label>
              <select class="form-select form-select-sm" name="members[<?= $index ?>][gender]" required>
                <option value="">Select</option>
                <option value="MALE" <?= $member['gender']==='MALE'?'selected':'' ?>>Male</option>
                <option value="FEMALE" <?= $member['gender']==='FEMALE'?'selected':'' ?>>Female</option>
                <option value="OTHER" <?= $member['gender']==='OTHER'?'selected':'' ?>>Other</option>
              </select>
            </div>
          </div>
          <div class="row">
            <div class="col-md-6 mb-2">
              <label class="form-label">Guardian Name</label>
              <input type="text" class="form-control form-control-sm" name="members[<?= $index ?>][guardian_name]" value="<?= htmlspecialchars($member['guardian_name'] ?? '') ?>" maxlength="120">
            </div>
            <div class="col-md-6 mb-2">
              <label class="form-label">Guardian Phone</label>
              <input type="tel" class="form-control form-control-sm" name="members[<?= $index ?>][guardian_phone]" value="<?= htmlspecialchars($member['guardian_phone'] ?? '') ?>" maxlength="50">
            </div>
          </div>
          <div class="mb-2">
            <label class="form-label">Address</label>
            <textarea class="form-control form-control-sm" name="members[<?= $index ?>][address]" rows="1" maxlength="255"><?= htmlspecialchars($member['address'] ?? '') ?></textarea>
          </div>
        </div>
      </div>
      <?php
        }
      }
      ?>
    </div>
    <div class="text-center mt-3">
      <button type="button" class="btn btn-success" id="add-member">
        <i class="bi bi-plus-circle me-2"></i>Add New Member
      </button>
    </div>
    <script>
    // Add/remove member JS
    let memberCount = <?= count($members ?? []) ?>;
    document.getElementById('add-member')?.addEventListener('click', function() {
      const container = document.getElementById('members-container');
      const index = memberCount;
      const div = document.createElement('div');
      div.className = 'member-card card mb-3';
      div.innerHTML = `
        <div class="card-header bg-light py-2 d-flex justify-content-between align-items-center">
          <span class="fw-bold text-primary">Member ${index + 1}</span>
          <button type="button" class="btn btn-outline-danger btn-sm remove-member">Remove</button>
        </div>
        <div class="card-body">
          <div class="row">
            <div class="col-md-6 mb-2">
              <label class="form-label">Full Name</label>
              <input type="text" class="form-control form-control-sm" name="members[${index}][name]" required maxlength="120">
            </div>
            <div class="col-md-3 mb-2">
              <label class="form-label">Age</label>
              <input type="number" class="form-control form-control-sm" name="members[${index}][age]" min="5" max="21" required>
            </div>
            <div class="col-md-3 mb-2">
              <label class="form-label">Gender</label>
              <select class="form-select form-select-sm" name="members[${index}][gender]" required>
                <option value="">Select</option>
                <option value="MALE">Male</option>
                <option value="FEMALE">Female</option>
                <option value="OTHER">Other</option>
              </select>
            </div>
          </div>
          <div class="row">
            <div class="col-md-6 mb-2">
              <label class="form-label">Guardian Name</label>
              <input type="text" class="form-control form-control-sm" name="members[${index}][guardian_name]" maxlength="120">
            </div>
            <div class="col-md-6 mb-2">
              <label class="form-label">Guardian Phone</label>
              <input type="tel" class="form-control form-control-sm" name="members[${index}][guardian_phone]" maxlength="50">
            </div>
          </div>
          <div class="mb-2">
            <label class="form-label">Address</label>
            <textarea class="form-control form-control-sm" name="members[${index}][address]" rows="1" maxlength="255"></textarea>
          </div>
        </div>
      `;
      container.appendChild(div);
      memberCount++;
    });
    document.getElementById('members-container')?.addEventListener('click', function(e) {
      if (e.target.closest('.remove-member')) {
        e.target.closest('.member-card').remove();
        // Renumber member labels if needed
      }
    });
    </script>
    <?php endif; ?>
    <button type="submit" class="btn btn-primary">Update</button>
    <a href="participants.php" class="btn btn-secondary">Cancel</a>
  </form>
  <script>
    // JS for cascading dropdowns (district->block->gp->school)
    async function loadBlocks(districtId) {
      const blockSelect = document.getElementById('update-block');
      const gpSelect = document.getElementById('update-gp');
      const schoolSelect = document.getElementById('update-school');
      blockSelect.disabled = true; gpSelect.disabled = true; schoolSelect.disabled = true;
      blockSelect.innerHTML = '<option value="">Select Block</option>';
      gpSelect.innerHTML = '<option value="">Select GP</option>';
      schoolSelect.innerHTML = '<option value="">Select School</option>';
      if (!districtId) return;
      try {
        const response = await fetch('/school-crm/api/blocks.php?district_id='+encodeURIComponent(districtId));
        const blocks = await response.json();
        blocks.forEach(block => {
          blockSelect.innerHTML += `<option value="${block.id}">${block.name}</option>`;
        });
        blockSelect.disabled = false;
      } catch (e) { console.error(e); }
    }
    async function loadGps(blockId) {
      const gpSelect = document.getElementById('update-gp');
      const schoolSelect = document.getElementById('update-school');
      gpSelect.disabled = true; schoolSelect.disabled = true;
      gpSelect.innerHTML = '<option value="">Select GP</option>';
      schoolSelect.innerHTML = '<option value="">Select School</option>';
      if (!blockId) return;
      try {
        const response = await fetch('/school-crm/api/gps.php?block_id='+encodeURIComponent(blockId));
        const gps = await response.json();
        gps.forEach(gp => {
          gpSelect.innerHTML += `<option value="${gp.id}">${gp.name}</option>`;
        });
        gpSelect.disabled = false;
      } catch (e) { console.error(e); }
    }
    async function loadSchools(gpId) {
      const schoolSelect = document.getElementById('update-school');
      schoolSelect.disabled = true;
      schoolSelect.innerHTML = '<option value="">Select School</option>';
      if (!gpId) return;
      try {
        const response = await fetch('/school-crm/api/schools.php?gp_id='+encodeURIComponent(gpId));
        const schools = await response.json();
        schools.forEach(school => {
          schoolSelect.innerHTML += `<option value="${school.id}">${school.name}</option>`;
        });
        schoolSelect.disabled = false;
      } catch (e) { console.error(e); }
    }
    document.getElementById('update-district').addEventListener('change', function() {
      loadBlocks(this.value);
    });
    document.getElementById('update-block').addEventListener('change', function() {
      loadGps(this.value);
    });
    document.getElementById('update-gp').addEventListener('change', function() {
      loadSchools(this.value);
    });
    // Preload blocks/gps/schools for current participant
    window.addEventListener('DOMContentLoaded', function() {
      const districtId = document.getElementById('update-district').value;
      const blockId = "<?= htmlspecialchars($participant['block_id']) ?>";
      const gpId = "<?= htmlspecialchars($participant['gp_id']) ?>";
      const schoolId = "<?= htmlspecialchars($participant['school_id']) ?>";
      if (districtId) {
        loadBlocks(districtId).then(() => {
          if (blockId) {
            document.getElementById('update-block').value = blockId;
            loadGps(blockId).then(() => {
              if (gpId) {
                document.getElementById('update-gp').value = gpId;
                loadSchools(gpId).then(() => {
                  if (schoolId) {
                    document.getElementById('update-school').value = schoolId;
                  }
                });
              }
            });
          }
        });
      }
    });
  </script>
</div>
<?php require_once __DIR__ . "/partials/footer.php"; ?>
