<?php
/**
 * Conference Registration
 * GHAMECC Choir Management Platform
 * 
 * This page allows members to register for conferences.
 */

// Include authentication functions
require_once '../includes/auth.php';

// Require login
requireLogin();

// Set base path for includes
$basePath = '..';

// Check if conference ID is provided
if (!isset($_GET['conference_id']) || !is_numeric($_GET['conference_id'])) {
    header("Location: index.php");
    exit("Invalid conference ID");
}

$conferenceId = (int)$_GET['conference_id'];
$userId = $_SESSION['user_id'];

// Get conference details
$conference = fetchRow("SELECT c.*, 
                        CASE 
                            WHEN c.type = 'circuit' THEN (SELECT name FROM circuits WHERE id = c.entity_id)
                            WHEN c.type = 'diocese' THEN (SELECT name FROM dioceses WHERE id = c.entity_id)
                            WHEN c.type = 'connexional' THEN 'Connexional Office'
                        END AS entity_name
                        FROM conferences c
                        WHERE c.id = $conferenceId");

if (!$conference) {
    header("Location: index.php");
    exit("Conference not found");
}

// Check if registration is allowed
$today = date('Y-m-d');
$registrationOpen = true;
$registrationMessage = '';

if ($conference['registration_deadline'] < $today) {
    $registrationOpen = false;
    $registrationMessage = 'Registration deadline has passed.';
} else if ($conference['status'] === 'cancelled') {
    $registrationOpen = false;
    $registrationMessage = 'This conference has been cancelled.';
} else if ($conference['status'] === 'completed') {
    $registrationOpen = false;
    $registrationMessage = 'This conference has already taken place.';
}

// Check if maximum participants reached
$registrationCount = fetchValue("SELECT COUNT(*) FROM conference_registrations WHERE conference_id = $conferenceId");
if ($conference['max_participants'] && $registrationCount >= $conference['max_participants']) {
    $registrationOpen = false;
    $registrationMessage = 'Registration is full. Maximum participants reached.';
}

// Get member details
$member = fetchRow("SELECT * FROM members WHERE user_id = $userId");
if (!$member) {
    header("Location: ../members/create.php?redirect=conferences/register.php?conference_id=$conferenceId");
    exit("You must create a member profile before registering for conferences");
}

// Check if already registered
$existingRegistration = fetchRow("SELECT * FROM conference_registrations WHERE conference_id = $conferenceId AND member_id = {$member['id']}");
if ($existingRegistration) {
    header("Location: my_registration.php?conference_id=$conferenceId");
    exit("You are already registered for this conference");
}

// Check if user has permission to register based on conference type and entity
$hasPermission = true;
$permissionMessage = '';

if ($conference['type'] === 'circuit') {
    // Check if member belongs to a society in this circuit
    $memberSociety = fetchRow("SELECT s.circuit_id FROM societies s 
                              JOIN members m ON m.society_id = s.id 
                              WHERE m.id = {$member['id']}");
    
    if (!$memberSociety || $memberSociety['circuit_id'] != $conference['entity_id']) {
        $hasPermission = false;
        $permissionMessage = 'You must be a member of a society in this circuit to register for this conference.';
    }
} else if ($conference['type'] === 'diocese') {
    // Check if member belongs to a society in this diocese
    $memberDiocese = fetchRow("SELECT c.diocese_id FROM circuits c 
                              JOIN societies s ON s.circuit_id = c.id
                              JOIN members m ON m.society_id = s.id 
                              WHERE m.id = {$member['id']}");
    
    if (!$memberDiocese || $memberDiocese['diocese_id'] != $conference['entity_id']) {
        $hasPermission = false;
        $permissionMessage = 'You must be a member of a society in this diocese to register for this conference.';
    }
}

// Process form submission
$errors = [];
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $registrationOpen && $hasPermission) {
    // Validate inputs
    $accommodationNeeded = isset($_POST['accommodation_needed']) ? 1 : 0;
    $paymentMethod = mysqli_real_escape_string($conn, $_POST['payment_method'] ?? '');
    $specialRequests = mysqli_real_escape_string($conn, $_POST['special_requests'] ?? '');
    $emergencyContact = mysqli_real_escape_string($conn, $_POST['emergency_contact'] ?? '');
    $emergencyPhone = mysqli_real_escape_string($conn, $_POST['emergency_phone'] ?? '');
    
    // Validate payment method
    if (empty($paymentMethod)) {
        $errors[] = 'Payment method is required.';
    }
    
    // Validate emergency contact information if accommodation is needed
    if ($accommodationNeeded) {
        if (empty($emergencyContact)) {
            $errors[] = 'Emergency contact name is required when requesting accommodation.';
        }
        if (empty($emergencyPhone)) {
            $errors[] = 'Emergency contact phone is required when requesting accommodation.';
        }
    }
    
    // If no errors, insert the registration
    if (empty($errors)) {
        $query = "INSERT INTO conference_registrations (conference_id, member_id, registration_date, payment_status, payment_method, accommodation_needed, special_requests, emergency_contact, emergency_phone) 
                  VALUES ($conferenceId, {$member['id']}, CURDATE(), 'pending', '$paymentMethod', $accommodationNeeded, '$specialRequests', '$emergencyContact', '$emergencyPhone')";
        
        $result = executeQuery($query);
        
        if ($result) {
            $registrationId = mysqli_insert_id($conn);
            $success = true;
        } else {
            $errors[] = 'Error registering for conference: ' . mysqli_error($conn);
        }
    }
}

// Format dates for display
$startDate = date('F j, Y', strtotime($conference['start_date']));
$endDate = date('F j, Y', strtotime($conference['end_date']));
$registrationDeadline = date('F j, Y', strtotime($conference['registration_deadline']));
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register for <?php echo htmlspecialchars($conference['name']); ?> - GHAMECC Choir Management</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Custom CSS -->
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <!-- Navigation -->
    <?php include '../includes/navbar.php'; ?>
    
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <?php include '../includes/sidebar.php'; ?>
            
            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">Register for Conference</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a href="view.php?id=<?php echo $conferenceId; ?>" class="btn btn-sm btn-secondary">
                            <i class="fas fa-arrow-left me-1"></i> Back to Conference
                        </a>
                    </div>
                </div>
                
                <?php if ($success): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="fas fa-check-circle me-2"></i> You have successfully registered for this conference!
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <div class="text-center my-4">
                    <a href="my_registration.php?conference_id=<?php echo $conferenceId; ?>" class="btn btn-primary">
                        <i class="fas fa-id-card me-2"></i> View My Registration
                    </a>
                </div>
                <?php else: ?>
                
                <?php if (!$registrationOpen): ?>
                <div class="alert alert-warning" role="alert">
                    <i class="fas fa-exclamation-triangle me-2"></i> <?php echo htmlspecialchars($registrationMessage); ?>
                </div>
                <?php endif; ?>
                
                <?php if (!$hasPermission): ?>
                <div class="alert alert-danger" role="alert">
                    <i class="fas fa-ban me-2"></i> <?php echo htmlspecialchars($permissionMessage); ?>
                </div>
                <?php endif; ?>
                
                <?php if (!empty($errors)): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <strong>Please fix the following errors:</strong>
                    <ul class="mb-0">
                        <?php foreach ($errors as $error): ?>
                            <li><?php echo htmlspecialchars($error); ?></li>
                        <?php endforeach; ?>
                    </ul>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php endif; ?>
                
                <div class="row">
                    <div class="col-md-8">
                        <div class="card shadow mb-4">
                            <div class="card-header py-3">
                                <h6 class="m-0 font-weight-bold text-primary">Registration Form</h6>
                            </div>
                            <div class="card-body">
                                <?php if ($registrationOpen && $hasPermission): ?>
                                <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'] . '?conference_id=' . $conferenceId); ?>">
                                    <div class="mb-3">
                                        <label class="form-label">Member Information</label>
                                        <div class="card">
                                            <div class="card-body">
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <p><strong>Name:</strong> <?php echo htmlspecialchars($member['first_name'] . ' ' . $member['surname']); ?></p>
                                                        <p><strong>Email:</strong> <?php echo htmlspecialchars($member['email']); ?></p>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <p><strong>Phone:</strong> <?php echo htmlspecialchars($member['contact_number_1']); ?></p>
                                                        <p><strong>Society:</strong> 
                                                            <?php 
                                                            $society = fetchRow("SELECT name FROM societies WHERE id = {$member['society_id']}");
                                                            echo htmlspecialchars($society['name'] ?? 'Not assigned');
                                                            ?>
                                                        </p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="payment_method" class="form-label">Payment Method <span class="text-danger">*</span></label>
                                        <select class="form-select" id="payment_method" name="payment_method" required>
                                            <option value="">Select Payment Method</option>
                                            <option value="mobile_money" <?php echo (isset($_POST['payment_method']) && $_POST['payment_method'] === 'mobile_money') ? 'selected' : ''; ?>>Mobile Money</option>
                                            <option value="bank_transfer" <?php echo (isset($_POST['payment_method']) && $_POST['payment_method'] === 'bank_transfer') ? 'selected' : ''; ?>>Bank Transfer</option>
                                            <option value="cash" <?php echo (isset($_POST['payment_method']) && $_POST['payment_method'] === 'cash') ? 'selected' : ''; ?>>Cash</option>
                                        </select>
                                        <div class="form-text">You will need to complete payment to confirm your registration.</div>
                                    </div>
                                    
                                    <div class="mb-3 form-check">
                                        <input type="checkbox" class="form-check-input" id="accommodation_needed" name="accommodation_needed" <?php echo (isset($_POST['accommodation_needed'])) ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="accommodation_needed">I need accommodation during the conference</label>
                                    </div>
                                    
                                    <div id="accommodation_details" class="card mb-3 p-3 border-info" style="display: none;">
                                        <div class="mb-3">
                                            <label for="emergency_contact" class="form-label">Emergency Contact Name</label>
                                            <input type="text" class="form-control" id="emergency_contact" name="emergency_contact" value="<?php echo $_POST['emergency_contact'] ?? ''; ?>">
                                        </div>
                                        <div class="mb-3">
                                            <label for="emergency_phone" class="form-label">Emergency Contact Phone</label>
                                            <input type="text" class="form-control" id="emergency_phone" name="emergency_phone" value="<?php echo $_POST['emergency_phone'] ?? ''; ?>">
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="special_requests" class="form-label">Special Requests or Notes</label>
                                        <textarea class="form-control" id="special_requests" name="special_requests" rows="3"><?php echo $_POST['special_requests'] ?? ''; ?></textarea>
                                        <div class="form-text">Please mention any dietary restrictions, accessibility needs, or other special requirements.</div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <div class="alert alert-info">
                                            <i class="fas fa-info-circle me-2"></i> By registering for this conference, you agree to abide by all conference rules and regulations.
                                        </div>
                                    </div>
                                    
                                    <div class="d-grid gap-2">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-user-plus me-2"></i> Complete Registration
                                        </button>
                                    </div>
                                </form>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="card shadow mb-4">
                            <div class="card-header py-3">
                                <h6 class="m-0 font-weight-bold text-primary">Conference Information</h6>
                            </div>
                            <div class="card-body">
                                <h5><?php echo htmlspecialchars($conference['name']); ?></h5>
                                <p class="text-muted">
                                    <i class="fas fa-map-marker-alt me-2"></i> <?php echo htmlspecialchars($conference['venue']); ?>
                                </p>
                                
                                <hr>
                                
                                <div class="mb-3">
                                    <h6 class="text-primary">Dates</h6>
                                    <p><i class="far fa-calendar-alt me-2"></i> <?php echo $startDate; ?> to <?php echo $endDate; ?></p>
                                    <p><i class="far fa-clock me-2"></i> Registration Deadline: <?php echo $registrationDeadline; ?></p>
                                </div>
                                
                                <div class="mb-3">
                                    <h6 class="text-primary">Registration Fee</h6>
                                    <p><i class="fas fa-money-bill-wave me-2"></i> GH₵<?php echo number_format($conference['fee_amount'], 2); ?></p>
                                </div>
                                
                                <div class="mb-3">
                                    <h6 class="text-primary">Entity</h6>
                                    <p><i class="fas fa-sitemap me-2"></i> <?php echo htmlspecialchars($conference['entity_name']); ?> (<?php echo ucfirst($conference['type']); ?>)</p>
                                </div>
                                
                                <?php if (!empty($conference['description'])): ?>
                                <div class="mb-3">
                                    <h6 class="text-primary">Description</h6>
                                    <p class="small"><?php echo nl2br(htmlspecialchars($conference['description'])); ?></p>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <div class="card shadow mb-4">
                            <div class="card-header py-3">
                                <h6 class="m-0 font-weight-bold text-primary">Payment Instructions</h6>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <h6>Mobile Money</h6>
                                    <p>Send payment to: <strong>0244123456</strong></p>
                                    <p>Name: <strong>GHAMECC Treasurer</strong></p>
                                    <p class="small">Use your full name and conference ID as reference.</p>
                                </div>
                                
                                <div class="mb-3">
                                    <h6>Bank Transfer</h6>
                                    <p>Bank: <strong>Ghana Commercial Bank</strong></p>
                                    <p>Account Name: <strong>GHAMECC Conference</strong></p>
                                    <p>Account Number: <strong>1234567890</strong></p>
                                    <p class="small">Use your full name and conference ID as reference.</p>
                                </div>
                                
                                <div class="mb-3">
                                    <h6>Cash Payment</h6>
                                    <p>Pay directly to your Circuit or Diocese Treasurer.</p>
                                    <p class="small">Ensure you receive an official receipt.</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </main>
        </div>
    </div>
    
    <!-- Bootstrap JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Toggle accommodation details based on checkbox
            function toggleAccommodationDetails() {
                if ($('#accommodation_needed').is(':checked')) {
                    $('#accommodation_details').slideDown();
                    $('#emergency_contact, #emergency_phone').prop('required', true);
                } else {
                    $('#accommodation_details').slideUp();
                    $('#emergency_contact, #emergency_phone').prop('required', false);
                }
            }
            
            // Initial state
            toggleAccommodationDetails();
            
            // Handle checkbox change
            $('#accommodation_needed').change(function() {
                toggleAccommodationDetails();
            });
        });
    </script>
</body>
</html>
