<?php
declare(strict_types=1);

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ============ HELPER FUNCTIONS ============
function csrf_token() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function csrf_validate($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

// Database connection using your existing database
try {
    $db = new PDO(
        "mysql:host=localhost;dbname=oned350261_scsgdth;charset=utf8mb4",
        "oned350261_scsgdth2026", // Change to your DB username
        "Bijoy@1881G",     // Change to your DB password
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false
        ]
    );
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// ============ MAIN REGISTRATION CLASS ============
class ParticipantRegistration {
    private PDO $db;
    private array $errors = [];
    private array $success = [];
    
    public function __construct(PDO $db) {
        $this->db = $db;
    }
    
    /**
     * Generate next registration number
     * Format: GDTH2026 + 5 digits (GDTH202600001)
     */
    private function generateRegNo(): string {
        $stmt = $this->db->query("
            SELECT MAX(CAST(SUBSTRING(reg_no, -5) AS UNSIGNED)) as max_num 
            FROM participants 
            WHERE reg_no LIKE 'GDTH2026%'
        ");
        $result = $stmt->fetch();
        $nextNum = ($result['max_num'] ?? 0) + 1;
        return 'GDTH2026' . str_pad((string)$nextNum, 5, '0', STR_PAD_LEFT);
    }
    
    /**
     * Generate next group name
     * Format: GDTH_GROUP_00001
     */
    private function generateGroupName(): string {
        $stmt = $this->db->query("
            SELECT MAX(CAST(SUBSTRING(group_name, -5) AS UNSIGNED)) as max_num 
            FROM participants 
            WHERE group_name LIKE 'GDTH_GROUP_%'
        ");
        $result = $stmt->fetch();
        $nextNum = ($result['max_num'] ?? 0) + 1;
        return 'GDTH_GROUP_' . str_pad((string)$nextNum, 5, '0', STR_PAD_LEFT);
    }
    
    /**
     * Process solo registration
     */
    public function processSolo(array $post): bool {
        if (!csrf_validate($post['csrf_token'] ?? '')) {
            $this->errors[] = 'Invalid security token';
            return false;
        }
        
        $required = ['full_name', 'age', 'gender', 'guardian_name', 'guardian_phone', 
                     'address', 'district_id', 'block_id', 'gp_id', 'school_id'];
        
        foreach ($required as $field) {
            if (empty($post[$field])) {
                $this->errors[] = ucfirst(str_replace('_', ' ', $field)) . ' is required';
            }
        }
        
        $age = (int)($post['age'] ?? 0);
        if ($age < 5 || $age > 21) {
            $this->errors[] = 'Age must be between 5 and 21';
        }
        
        if (!empty($post['gender']) && !in_array($post['gender'], ['MALE', 'FEMALE', 'OTHER'])) {
            $this->errors[] = 'Invalid gender value';
        }
        
        if (!empty($this->errors)) {
            return false;
        }
        
        try {
            $this->db->beginTransaction();
            
            $regNo = $this->generateRegNo();
            
            $stmt = $this->db->prepare("
                INSERT INTO participants (
                    reg_no, full_name, age, gender, guardian_name, 
                    guardian_phone, whatsapp, optional_phone, address, district_id, block_id, gp_id, 
                    school_id, category, dance_type, notes, consent, created_at
                ) VALUES (
                    :reg_no, :full_name, :age, :gender, :guardian_name,
                    :guardian_phone, :whatsapp, :optional_phone, :address, :district_id, :block_id, :gp_id,
                    :school_id, 'SOLO', :dance_type, :notes, 1, NOW()
                )
            ");
            
            $stmt->execute([
                ':reg_no' => $regNo,
                ':full_name' => $post['full_name'],
                ':age' => $age,
                ':gender' => $post['gender'],
                ':guardian_name' => $post['guardian_name'],
                ':guardian_phone' => $post['guardian_phone'],
                ':whatsapp' => $post['whatsapp'] ?? null,
                ':optional_phone' => $post['optional_phone'] ?? null,
                ':address' => $post['address'],
                ':district_id' => $post['district_id'],
                ':block_id' => $post['block_id'],
                ':gp_id' => $post['gp_id'],
                ':school_id' => $post['school_id'],
                ':dance_type' => $post['dance_type'] ?: null,
                ':notes' => $post['notes'] ?: null
            ]);
            
            $this->db->commit();
            $this->success[] = "Registration successful! Registration No: {$regNo}";
            $this->success[] = "Please note down this registration number for future reference.";
            return true;
            
        } catch (PDOException $e) {
            $this->db->rollBack();
            $this->errors[] = 'Database error: ' . $e->getMessage();
            return false;
        }
    }
    
    /**
     * Process group registration with separate group_members table
     */
    public function processGroup(array $post): bool {
        if (!csrf_validate($post['csrf_token'] ?? '')) {
            $this->errors[] = 'Invalid security token';
            return false;
        }
        
        $required = ['full_name', 'age', 'gender', 'guardian_name', 'guardian_phone',
                     'address', 'district_id', 'block_id', 'gp_id', 'school_id'];
        
        foreach ($required as $field) {
            if (empty($post[$field])) {
                $this->errors[] = ucfirst(str_replace('_', ' ', $field)) . ' is required';
            }
        }
        
        $age = (int)($post['age'] ?? 0);
        if ($age < 5 || $age > 21) {
            $this->errors[] = 'Leader age must be between 5 and 21';
        }
        
        // Validate group members
        $members = [];
        if (empty($post['members']) || !is_array($post['members'])) {
            $this->errors[] = 'At least one group member is required';
        } else {
            foreach ($post['members'] as $index => $member) {
                $memberErrors = [];
                
                if (empty($member['name'])) {
                    $memberErrors[] = "Member " . ($index + 1) . ": Name is required";
                }
                
                $memberAge = (int)($member['age'] ?? 0);
                if ($memberAge < 5 || $memberAge > 21) {
                    $memberErrors[] = "Member " . ($index + 1) . ": Age must be between 5 and 21";
                }
                
                if (empty($member['gender']) || !in_array($member['gender'], ['MALE', 'FEMALE', 'OTHER'])) {
                    $memberErrors[] = "Member " . ($index + 1) . ": Valid gender is required";
                }
                
                if (!empty($memberErrors)) {
                    $this->errors = array_merge($this->errors, $memberErrors);
                } else {
                    $members[] = $member;
                }
            }
        }
        
        if (!empty($this->errors)) {
            return false;
        }
        
        try {
            $this->db->beginTransaction();
            
            $regNo = $this->generateRegNo();
            $groupName = $this->generateGroupName();
            $groupSize = 1 + count($members); // Leader + members
            
            // Insert group leader as participant
            $stmt = $this->db->prepare("
                INSERT INTO participants (
                    reg_no, full_name, age, gender, guardian_name,
                    guardian_phone, whatsapp, optional_phone, address, district_id, block_id, gp_id,
                    school_id, category, dance_type, group_name, group_size,
                    notes, consent, created_at
                ) VALUES (
                    :reg_no, :full_name, :age, :gender, :guardian_name,
                    :guardian_phone, :whatsapp, :optional_phone, :address, :district_id, :block_id, :gp_id,
                    :school_id, 'GROUP', :dance_type, :group_name, :group_size,
                    :notes, 1, NOW()
                )
            ");
            
            $stmt->execute([
                ':reg_no' => $regNo,
                ':full_name' => $post['full_name'],
                ':age' => $age,
                ':gender' => $post['gender'],
                ':guardian_name' => $post['guardian_name'],
                ':guardian_phone' => $post['guardian_phone'],
                ':whatsapp' => $post['whatsapp'] ?? null,
                ':optional_phone' => $post['optional_phone'] ?? null,
                ':address' => $post['address'],
                ':district_id' => $post['district_id'],
                ':block_id' => $post['block_id'],
                ':gp_id' => $post['gp_id'],
                ':school_id' => $post['school_id'],
                ':dance_type' => $post['dance_type'] ?: null,
                ':group_name' => $groupName,
                ':group_size' => $groupSize,
                ':notes' => $post['notes'] ?: null
            ]);
            
            // Get the inserted participant's ID
            $participantId = (int)$this->db->lastInsertId();
            
            // Insert group members into group_members table
            $stmt = $this->db->prepare("
                INSERT INTO group_members (
                    participant_id, name, age, gender, guardian_name, guardian_phone, address
                ) VALUES (
                    :participant_id, :name, :age, :gender, :guardian_name, :guardian_phone, :address
                )
            ");
            
            foreach ($members as $member) {
                $stmt->execute([
                    ':participant_id' => $participantId,
                    ':name' => $member['name'],
                    ':age' => (int)$member['age'],
                    ':gender' => $member['gender'],
                    ':guardian_name' => $member['guardian_name'] ?? null,
                    ':guardian_phone' => $member['guardian_phone'] ?? null,
                    ':address' => $member['address'] ?? null
                ]);
            }
            
            $this->db->commit();
            $this->success[] = "Group registration successful!";
            $this->success[] = "Group Name: {$groupName}";
            $this->success[] = "Registration No: {$regNo}";
            $this->success[] = "Total Members: " . $groupSize . " (Leader + " . count($members) . " members)";
            return true;
            
        } catch (PDOException $e) {
            $this->db->rollBack();
            $this->errors[] = 'Database error: ' . $e->getMessage();
            return false;
        }
    }
    
    public function getErrors(): array {
        return $this->errors;
    }
    
    public function getSuccess(): array {
        return $this->success;
    }
}

// ============ PROCESS FORM SUBMISSION ============
$registration = new ParticipantRegistration($db);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $category = $_POST['category'] ?? '';
    $success = false;
    if ($category === 'SOLO') {
        if ($registration->processSolo($_POST)) {
            $success = true;
        }
    } elseif ($category === 'GROUP') {
        if ($registration->processGroup($_POST)) {
            $success = true;
        }
    }
    if ($success) {
        // Store success messages in session for display after redirect
        $_SESSION['registration_success'] = $registration->getSuccess();
        // Prevent resubmission on refresh (PRG pattern)
        header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?') . '?success=1');
        exit;
    }
}


$csrfToken = csrf_token();

// Fetch districts for dropdown
$districts = $db->query("SELECT id, name FROM districts ORDER BY name")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dance Talent Hunt 2026 - Registration Form</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px 0;
        }
        .registration-card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            overflow: hidden;
        }
        .card-header {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            border-bottom: none;
        }
        .nav-tabs .nav-link {
            border: none;
            color: #6c757d;
            font-weight: 600;
            padding: 12px 25px;
            border-radius: 0;
        }
        .nav-tabs .nav-link.active {
            color: #667eea;
            background: transparent;
            border-bottom: 3px solid #667eea;
        }
        .btn-primary {
            background: linear-gradient(45deg, #667eea, #764ba2);
            border: none;
            padding: 10px 30px;
            border-radius: 25px;
            font-weight: 600;
            transition: transform 0.2s;
        }
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
        }
        .member-card {
            border-left: 4px solid #667eea;
            border-radius: 10px;
            background: #f8f9fa;
            transition: all 0.3s;
        }
        .member-card:hover {
            background: #fff;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .alert-success {
            background: linear-gradient(45deg, #28a745, #20c997);
            color: white;
            border: none;
        }
        .alert-danger {
            background: linear-gradient(45deg, #dc3545, #c82333);
            color: white;
            border: none;
        }
        .alert i {
            font-size: 1.2rem;
        }
        .form-label {
            font-weight: 600;
            color: #495057;
        }
        .form-control:focus, .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        .id-card {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            margin-top: 20px;
        }
        .id-card h3 {
            font-size: 2rem;
            font-weight: bold;
            letter-spacing: 2px;
            margin: 10px 0;
            background: rgba(255,255,255,0.2);
            padding: 10px;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-11 col-lg-10">
                <div class="card registration-card">
                    <div class="card-header text-center py-4">
                        <h2 class="mb-0"><i class="bi bi-music-note-beamed me-2"></i>Dance Talent Hunt 2026</h2>
                        <p class="mb-0 mt-2 opacity-75">Participant Registration Form</p>
                    </div>
                    
                    <div class="card-body p-4">
                        <!-- Alerts -->
                        <?php if (!empty($registration->getErrors())): ?>
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <i class="bi bi-exclamation-triangle-fill me-2"></i>
                                <strong>Please fix the following errors:</strong>
                                <ul class="mb-0 mt-2">
                                    <?php foreach ($registration->getErrors() as $error): ?>
                                        <li><?= htmlspecialchars($error) ?></li>
                                    <?php endforeach; ?>
                                </ul>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>
                        
                        <?php
                        $showSuccess = false;
                        $successMessages = [];
                        if (isset($_GET['success']) && $_GET['success'] == '1' && !empty($_SESSION['registration_success'])) {
                            $showSuccess = true;
                            $successMessages = $_SESSION['registration_success'];
                            unset($_SESSION['registration_success']);
                        } elseif (!empty($registration->getSuccess())) {
                            $showSuccess = true;
                            $successMessages = $registration->getSuccess();
                        }
                        ?>
                        <?php if ($showSuccess): ?>
                            <div class="alert alert-success auto-hide-success" role="alert">
                                <i class="bi bi-check-circle-fill me-2"></i>
                                <strong>Congratulations! Registration Successful!</strong>
                                <ul class="mb-0 mt-2">
                                    <?php foreach ($successMessages as $success): ?>
                                        <li><?= htmlspecialchars($success) ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        <?php endif; ?>
                        
                        <!-- Tabs -->
                        <ul class="nav nav-tabs mb-4 justify-content-center" id="registrationTabs" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="solo-tab" data-bs-toggle="tab" 
                                        data-bs-target="#solo" type="button" role="tab">
                                    <i class="bi bi-person"></i> Solo Participant
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="group-tab" data-bs-toggle="tab" 
                                        data-bs-target="#group" type="button" role="tab">
                                    <i class="bi bi-people"></i> Group Participant
                                </button>
                            </li>
                        </ul>
                        
                        <!-- Tab Content -->
                        <div class="tab-content" id="registrationTabsContent">
                            <!-- SOLO FORM -->
                            <div class="tab-pane fade show active" id="solo" role="tabpanel">
                                <form method="POST" action="" class="needs-validation" novalidate>
                                    <input type="hidden" name="category" value="SOLO">
                                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">
                                    
                                    <h5 class="text-primary mb-3"><i class="bi bi-person-vcard me-2"></i>Personal Information</h5>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="solo-full_name" class="form-label">Full Name</label>
                                            <input type="text" class="form-control" id="solo-full_name" 
                                                   name="full_name" value="<?= htmlspecialchars($_POST['full_name'] ?? '') ?>" 
                                                   required maxlength="120" placeholder="Enter your full name">
                                            <div class="invalid-feedback">Full name is required</div>
                                        </div>
                                        
                                        <div class="col-md-3 mb-3">
                                            <label for="solo-age" class="form-label">Age (5-21 years)</label>
                                            <input type="number" class="form-control" id="solo-age" 
                                                   name="age" value="<?= htmlspecialchars($_POST['age'] ?? '') ?>" 
                                                   min="5" max="21" required placeholder="Age">
                                            <div class="invalid-feedback">Age must be between 5 and 21</div>
                                        </div>
                                        
                                        <div class="col-md-3 mb-3">
                                            <label for="solo-gender" class="form-label">Gender</label>
                                            <select class="form-select" id="solo-gender" name="gender" required>
                                                <option value="">Select Gender</option>
                                                <option value="MALE" <?= ($_POST['gender'] ?? '') === 'MALE' ? 'selected' : '' ?>>Male</option>
                                                <option value="FEMALE" <?= ($_POST['gender'] ?? '') === 'FEMALE' ? 'selected' : '' ?>>Female</option>
                                                <option value="OTHER" <?= ($_POST['gender'] ?? '') === 'OTHER' ? 'selected' : '' ?>>Other</option>
                                            </select>
                                            <div class="invalid-feedback">Please select gender</div>
                                        </div>
                                    </div>
                                    
                                    <h5 class="text-primary mb-3 mt-4"><i class="bi bi-people me-2"></i>Guardian Information</h5>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="solo-guardian_name" class="form-label">Guardian Name</label>
                                            <input type="text" class="form-control" id="solo-guardian_name" 
                                                   name="guardian_name" value="<?= htmlspecialchars($_POST['guardian_name'] ?? '') ?>" 
                                                   required maxlength="120" placeholder="Enter guardian's full name">
                                            <div class="invalid-feedback">Guardian name is required</div>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="solo-guardian_phone" class="form-label">Guardian Phone Number</label>
                                            <input type="tel" class="form-control" id="solo-guardian_phone" 
                                                   name="guardian_phone" value="<?= htmlspecialchars($_POST['guardian_phone'] ?? '') ?>" 
                                                   required maxlength="50" placeholder="Enter phone number">
                                            <div class="invalid-feedback">Guardian phone is required</div>
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label for="solo-whatsapp" class="form-label">WhatsApp Number</label>
                                            <div class="input-group">
                                                <input type="tel" class="form-control" id="solo-whatsapp" name="whatsapp" value="<?= htmlspecialchars($_POST['whatsapp'] ?? '') ?>" maxlength="50" placeholder="WhatsApp number">
                                                <button type="button" class="btn btn-outline-secondary" onclick="document.getElementById('solo-whatsapp').value = document.getElementById('solo-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 for="solo-optional_phone" class="form-label">Optional Phone Number</label>
                                            <input type="tel" class="form-control" id="solo-optional_phone" name="optional_phone" value="<?= htmlspecialchars($_POST['optional_phone'] ?? '') ?>" maxlength="50" placeholder="Other phone (optional)">
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="solo-address" class="form-label">Address</label>
                                        <textarea class="form-control" id="solo-address" name="address" 
                                                  rows="2" required maxlength="255" placeholder="Current address"><?= htmlspecialchars($_POST['address'] ?? '') ?></textarea>
                                        <div class="invalid-feedback">Address is required</div>
                                    </div>
                                    
                                    <h5 class="text-primary mb-3 mt-4"><i class="bi bi-building me-2"></i>School Information</h5>
                                    <div class="row">
                                        <div class="col-md-3 mb-3">
                                            <label for="solo-district" class="form-label">District</label>
                                            <select class="form-select" id="solo-district" name="district_id" required>
                                                <option value="">Select District</option>
                                                <?php foreach ($districts as $district): ?>
                                                    <option value="<?= htmlspecialchars($district['id']) ?>" <?= ($_POST['district_id'] ?? '') == $district['id'] ? 'selected' : '' ?>>
                                                        <?= htmlspecialchars($district['name']) ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                            <div class="invalid-feedback">Please select district</div>
                                        </div>
                                        <div class="col-md-3 mb-3">
                                            <label for="solo-block" class="form-label">Block</label>
                                            <select class="form-select" id="solo-block" name="block_id" required disabled>
                                                <option value="">Select Block</option>
                                            </select>
                                            <div class="invalid-feedback">Please select block</div>
                                        </div>
                                        <div class="col-md-3 mb-3">
                                            <label for="solo-gp" class="form-label">Gram Panchayat</label>
                                            <select class="form-select" id="solo-gp" name="gp_id" required disabled>
                                                <option value="">Select GP</option>
                                            </select>
                                            <div class="invalid-feedback">Please select GP</div>
                                        </div>
                                        <div class="col-md-3 mb-3">
                                            <label for="solo-school" class="form-label">School</label>
                                            <select class="form-select" id="solo-school" name="school_id" required disabled>
                                                <option value="">Select School</option>
                                            </select>
                                            <div class="invalid-feedback">Please select school</div>
                                        </div>
                                    </div>
                                    
                                    <h5 class="text-primary mb-3 mt-4"><i class="bi bi-music-note me-2"></i>Additional Information</h5>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="solo-dance_type" class="form-label">Dance Type</label>
                                            <input type="text" class="form-control" id="solo-dance_type" 
                                                   name="dance_type" value="<?= htmlspecialchars($_POST['dance_type'] ?? '') ?>"
                                                   maxlength="120" placeholder="e.g., Classical, Contemporary, Folk">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="solo-notes" class="form-label">Additional Notes</label>
                                            <textarea class="form-control" id="solo-notes" name="notes" rows="1" 
                                                      maxlength="255" placeholder="Any special requirements or notes"><?= htmlspecialchars($_POST['notes'] ?? '') ?></textarea>
                                        </div>
                                    </div>
                                    
                                    <div class="text-center mt-4">
                                        <button type="submit" class="btn btn-primary px-5 py-2">
                                            <i class="bi bi-save me-2"></i>Register Solo
                                        </button>
                                        <button type="reset" class="btn btn-outline-secondary px-4 py-2 ms-2">
                                            <i class="bi bi-arrow-counterclockwise me-2"></i>Reset Form
                                        </button>
                                    </div>
                                </form>
                            </div>
                            
                            <!-- GROUP FORM -->
                            <div class="tab-pane fade" id="group" role="tabpanel">
                                <form method="POST" action="" class="needs-validation" novalidate>
                                    <input type="hidden" name="category" value="GROUP">
                                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">
                                    
                                    <h5 class="text-primary mb-3"><i class="bi bi-person-badge me-2"></i>Group Leader Information</h5>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="group-full_name" class="form-label">Leader's Full Name</label>
                                            <input type="text" class="form-control" id="group-full_name" 
                                                   name="full_name" value="<?= htmlspecialchars($_POST['full_name'] ?? '') ?>" 
                                                   required maxlength="120" placeholder="Enter leader's full name">
                                        </div>
                                        <div class="col-md-3 mb-3">
                                            <label for="group-age" class="form-label">Age (5-21 years)</label>
                                            <input type="number" class="form-control" id="group-age" 
                                                   name="age" value="<?= htmlspecialchars($_POST['age'] ?? '') ?>" 
                                                   min="5" max="21" required placeholder="Age">
                                        </div>
                                        <div class="col-md-3 mb-3">
                                            <label for="group-gender" class="form-label">Gender</label>
                                            <select class="form-select" id="group-gender" name="gender" required>
                                                <option value="">Select Gender</option>
                                                <option value="MALE" <?= ($_POST['gender'] ?? '') === 'MALE' ? 'selected' : '' ?>>Male</option>
                                                <option value="FEMALE" <?= ($_POST['gender'] ?? '') === 'FEMALE' ? 'selected' : '' ?>>Female</option>
                                                <option value="OTHER" <?= ($_POST['gender'] ?? '') === 'OTHER' ? 'selected' : '' ?>>Other</option>
                                            </select>
                                        </div>
                                    </div>
                                    
                                    <h5 class="text-primary mb-3 mt-4"><i class="bi bi-people me-2"></i>Leader's Guardian Information</h5>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="group-guardian_name" class="form-label">Guardian Name</label>
                                            <input type="text" class="form-control" id="group-guardian_name" 
                                                   name="guardian_name" value="<?= htmlspecialchars($_POST['guardian_name'] ?? '') ?>" 
                                                   required maxlength="120" placeholder="Enter guardian's name">
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label for="group-guardian_phone" class="form-label">Guardian Phone</label>
                                            <input type="tel" class="form-control" id="group-guardian_phone" 
                                                   name="guardian_phone" value="<?= htmlspecialchars($_POST['guardian_phone'] ?? '') ?>" 
                                                   required maxlength="50" placeholder="Enter phone number">
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label for="group-whatsapp" class="form-label">WhatsApp Number</label>
                                            <div class="input-group">
                                                <input type="tel" class="form-control" id="group-whatsapp" name="whatsapp" value="<?= htmlspecialchars($_POST['whatsapp'] ?? '') ?>" maxlength="50" placeholder="WhatsApp number">
                                                <button type="button" class="btn btn-outline-secondary" onclick="document.getElementById('group-whatsapp').value = document.getElementById('group-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 for="group-optional_phone" class="form-label">Optional Phone Number</label>
                                            <input type="tel" class="form-control" id="group-optional_phone" name="optional_phone" value="<?= htmlspecialchars($_POST['optional_phone'] ?? '') ?>" maxlength="50" placeholder="Other phone (optional)">
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="group-address" class="form-label">Address</label>
                                        <textarea class="form-control" id="group-address" name="address" 
                                                  rows="2" required maxlength="255" placeholder="Leader's address"><?= htmlspecialchars($_POST['address'] ?? '') ?></textarea>
                                    </div>
                                    
                                    <h5 class="text-primary mb-3 mt-4"><i class="bi bi-building me-2"></i>School Information</h5>
                                    <div class="row">
                                        <div class="col-md-3 mb-3">
                                            <label for="group-district" class="form-label">District</label>
                                            <select class="form-select" id="group-district" name="district_id" required>
                                                <option value="">Select District</option>
                                                <?php foreach ($districts as $district): ?>
                                                    <option value="<?= htmlspecialchars($district['id']) ?>" <?= ($_POST['district_id'] ?? '') == $district['id'] ? 'selected' : '' ?>>
                                                        <?= htmlspecialchars($district['name']) ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-3 mb-3">
                                            <label for="group-block" class="form-label">Block</label>
                                            <select class="form-select" id="group-block" name="block_id" required disabled>
                                                <option value="">Select Block</option>
                                            </select>
                                        </div>
                                        <div class="col-md-3 mb-3">
                                            <label for="group-gp" class="form-label">Gram Panchayat</label>
                                            <select class="form-select" id="group-gp" name="gp_id" required disabled>
                                                <option value="">Select GP</option>
                                            </select>
                                        </div>
                                        <div class="col-md-3 mb-3">
                                            <label for="group-school" class="form-label">School</label>
                                            <select class="form-select" id="group-school" name="school_id" required disabled>
                                                <option value="">Select School</option>
                                            </select>
                                        </div>
                                    </div>
                                    
                                    <h5 class="text-primary mb-3 mt-4"><i class="bi bi-music-note me-2"></i>Additional Information</h5>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="group-dance_type" class="form-label">Dance Type</label>
                                            <input type="text" class="form-control" id="group-dance_type" 
                                                   name="dance_type" value="<?= htmlspecialchars($_POST['dance_type'] ?? '') ?>"
                                                   maxlength="120" placeholder="e.g., Classical, Contemporary, Folk">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="group-notes" class="form-label">Additional Notes</label>
                                            <textarea class="form-control" id="group-notes" name="notes" rows="1" 
                                                      maxlength="255" placeholder="Any special requirements or notes"><?= htmlspecialchars($_POST['notes'] ?? '') ?></textarea>
                                        </div>
                                    </div>
                                    
                                    <h5 class="text-primary mb-3 mt-4"><i class="bi bi-people me-2"></i>Group Members</h5>
                                    <div id="members-container"></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>
                                    
                                    <div class="row mt-3">
                                        <div class="col-md-4 mx-auto">
                                            <label class="form-label fw-bold text-center">Total Group Size</label>
                                            <input type="text" class="form-control text-center fw-bold" id="group-size" value="1 (Leader: 1)" readonly>
                                        </div>
                                    </div>
                                    
                                    <div class="text-center mt-4">
                                        <button type="submit" class="btn btn-primary px-5 py-2">
                                            <i class="bi bi-save me-2"></i>Register Group
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card-footer bg-light text-center py-3">
                        <small class="text-muted">
                            <i class="bi bi-info-circle me-1"></i>
                            After registration, you will receive a unique registration number that must be used for future reference
                        </small>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Member Template -->
    <template id="member-template">
        <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 <span class="member-number"></span></span>
                <button type="button" class="btn btn-outline-danger btn-sm remove-member">
                    <i class="bi bi-trash"></i> 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" placeholder="Member's full name">
                    </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 placeholder="Age">
                    </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" placeholder="Guardian's name (optional)">
                    </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" placeholder="Phone number (optional)">
                    </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" placeholder="Member's address (optional)"></textarea>
                </div>
            </div>
        </div>
    </template>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Auto-hide success alert after 5 seconds
        document.addEventListener('DOMContentLoaded', function() {
            const successAlert = document.querySelector('.auto-hide-success');
            if (successAlert) {
                setTimeout(() => {
                    successAlert.classList.add('fade');
                    setTimeout(() => successAlert.remove(), 500); // Remove after fade
                }, 5000);
            }
        });
        // ============ CASCADING DROPDOWNS ============
        async function loadBlocks(districtId, formId) {
            const blockSelect = document.getElementById(formId + '-block');
            const gpSelect = document.getElementById(formId + '-gp');
            const schoolSelect = document.getElementById(formId + '-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 (error) {
                console.error('Error loading blocks:', error);
            }
        }
        
        async function loadGps(blockId, formId) {
            const gpSelect = document.getElementById(formId + '-gp');
            const schoolSelect = document.getElementById(formId + '-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 (error) {
                console.error('Error loading GPs:', error);
            }
        }
        
        async function loadSchools(gpId, formId) {
            const schoolSelect = document.getElementById(formId + '-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 (error) {
                console.error('Error loading schools:', error);
            }
        }
        
        // ============ GROUP MEMBERS ============
        let memberCount = 0;
        
        function addMember() {
            const template = document.getElementById('member-template');
            const clone = template.content.cloneNode(true);
            const memberDiv = clone.querySelector('.member-card');
            
            memberDiv.querySelector('.member-number').textContent = memberCount + 1;
            
            memberDiv.querySelectorAll('[name*="INDEX"]').forEach(el => {
                el.name = el.name.replace('INDEX', memberCount);
                if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
                    el.value = '';
                } else if (el.tagName === 'SELECT') {
                    el.value = '';
                }
            });
            
            document.getElementById('members-container').appendChild(memberDiv);
            memberCount++;
            updateGroupSize();
        }
        
        function updateGroupSize() {
            const count = document.querySelectorAll('.member-card').length;
            const sizeElement = document.getElementById('group-size');
            if (sizeElement) {
                const totalSize = 1 + count;
                sizeElement.value = totalSize + ' (Leader: 1 + Members: ' + count + ')';
            }
        }
        
        // ============ FORM VALIDATION ============
        function validateForm(form) {
            let isValid = true;
            const requiredFields = form.querySelectorAll('[required]');
            
            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    field.classList.add('is-invalid');
                    isValid = false;
                } else {
                    field.classList.remove('is-invalid');
                }
            });
            
            return isValid;
        }
        
        // ============ INITIALIZATION ============
        document.addEventListener('DOMContentLoaded', function() {
            // District change handlers
            document.addEventListener('change', function(e) {
                if (e.target.id.endsWith('-district')) {
                    const formId = e.target.id.split('-')[0];
                    loadBlocks(e.target.value, formId);
                }
                if (e.target.id.endsWith('-block')) {
                    const formId = e.target.id.split('-')[0];
                    loadGps(e.target.value, formId);
                }
                if (e.target.id.endsWith('-gp')) {
                    const formId = e.target.id.split('-')[0];
                    loadSchools(e.target.value, formId);
                }
            });
            
            // Pre-load blocks if district is pre-selected
            const activeTab = document.querySelector('.tab-pane.active');
            if (activeTab) {
                const formId = activeTab.id;
                const districtSelect = document.getElementById(formId + '-district');
                if (districtSelect && districtSelect.value) {
                    loadBlocks(districtSelect.value, formId);
                }
            }
            
            // Add member button
            document.getElementById('add-member')?.addEventListener('click', addMember);
            
            // Remove member
            document.getElementById('members-container')?.addEventListener('click', function(e) {
                if (e.target.closest('.remove-member')) {
                    e.target.closest('.member-card').remove();
                    memberCount--;
                    
                    // Renumber remaining members
                    document.querySelectorAll('.member-card').forEach((card, index) => {
                        card.querySelector('.member-number').textContent = index + 1;
                        card.querySelectorAll('[name*="members["]').forEach(el => {
                            el.name = el.name.replace(/members\[\d+\]/, `members[${index}]`);
                        });
                    });
                    
                    updateGroupSize();
                }
            });
            
            // Form submission validation
            const forms = document.querySelectorAll('form');
            forms.forEach(form => {
                form.addEventListener('submit', function(e) {
                    if (!validateForm(this)) {
                        e.preventDefault();
                        e.stopPropagation();
                        
                        // Show error message
                        const alertDiv = document.createElement('div');
                        alertDiv.className = 'alert alert-warning alert-dismissible fade show mt-3';
                        alertDiv.innerHTML = `
                            <i class="bi bi-exclamation-triangle me-2"></i>
                            <strong>Warning!</strong> Please fill in all required fields.
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        `;
                        this.prepend(alertDiv);
                    }
                });
            });
            
            // Restore form data after validation failure
            <?php if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($registration->getErrors())): ?>
            setTimeout(() => {
                const formData = <?= json_encode($_POST) ?>;
                const activeTab = formData.category === 'GROUP' ? 'group' : 'solo';
                
                // Switch to correct tab
                document.getElementById(activeTab + '-tab').click();
                
                // Fill basic fields
                Object.keys(formData).forEach(key => {
                    if (key !== 'members' && key !== 'csrf_token') {
                        const input = document.querySelector(`#${activeTab}-${key}`);
                        if (input) input.value = formData[key];
                    }
                });
                
                // Handle members for group
                if (formData.members && Array.isArray(formData.members)) {
                    formData.members.forEach((member, index) => {
                        addMember();
                        const memberCard = document.querySelectorAll('.member-card')[index];
                        if (memberCard) {
                            Object.keys(member).forEach(field => {
                                const input = memberCard.querySelector(`[name="members[${index}][${field}]"]`);
                                if (input) input.value = member[field];
                            });
                        }
                    });
                }
                
                // Handle school chain
                if (formData.district_id) {
                    const districtSelect = document.getElementById(activeTab + '-district');
                    districtSelect.value = formData.district_id;
                    loadBlocks(formData.district_id, activeTab);
                    
                    setTimeout(() => {
                        if (formData.block_id) {
                            const blockSelect = document.getElementById(activeTab + '-block');
                            blockSelect.value = formData.block_id;
                            loadGps(formData.block_id, activeTab);
                            
                            setTimeout(() => {
                                if (formData.gp_id) {
                                    const gpSelect = document.getElementById(activeTab + '-gp');
                                    gpSelect.value = formData.gp_id;
                                    loadSchools(formData.gp_id, activeTab);
                                    
                                    setTimeout(() => {
                                        if (formData.school_id) {
                                            const schoolSelect = document.getElementById(activeTab + '-school');
                                            schoolSelect.value = formData.school_id;
                                        }
                                    }, 200);
                                }
                            }, 200);
                        }
                    }, 200);
                }
            }, 100);
            <?php endif; ?>
        });
    </script>
</body>
</html>