<?php
/**
 * Circuit Conference Setup
 * GHAMECC Choir Management Platform
 * 
 * This page allows circuit administrators to set up conferences for society members.
 */

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

// Require login
requireLogin();

// Check if user has appropriate permissions
if (!hasRole(['admin', 'circuit_chairman', 'circuit_secretary'])) {
    header("Location: ../index.php");
    exit("Unauthorized access");
}

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

// Get user's circuit information
$userId = $_SESSION['user_id'];
$userCircuit = null;
$isAdmin = hasRole(['admin']);

// If admin, they can manage any circuit
if ($isAdmin) {
    $circuits = fetchRows("SELECT c.*, d.name as diocese_name 
                          FROM circuits c 
                          JOIN dioceses d ON c.diocese_id = d.id 
                          ORDER BY d.name, c.name");
} else {
    // Get user's circuit role
    $circuitInfo = fetchRow("SELECT c.*, d.name as diocese_name 
                            FROM circuits c
                            JOIN dioceses d ON c.diocese_id = d.id
                            JOIN users u ON u.circuit_id = c.id
                            WHERE u.id = $userId");
    
    if ($circuitInfo) {
        $userCircuit = $circuitInfo;
        $circuits = [$circuitInfo];
    } else {
        // No circuit assigned
        header("Location: ../index.php");
        exit("No circuit assigned to your account");
    }
}

// Process form submission
$successMessage = '';
$errorMessage = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate inputs
    $errors = [];
    
    // Required fields
    $requiredFields = ['name', 'description', 'start_date', 'end_date', 'registration_deadline', 'venue', 'circuit_id', 'fee_amount'];
    foreach ($requiredFields as $field) {
        if (empty($_POST[$field])) {
            $errors[] = ucfirst(str_replace('_', ' ', $field)) . ' is required.';
        }
    }
    
    // Validate dates
    $today = date('Y-m-d');
    $startDate = $_POST['start_date'] ?? '';
    $endDate = $_POST['end_date'] ?? '';
    $registrationDeadline = $_POST['registration_deadline'] ?? '';
    
    if ($startDate && $endDate && $startDate > $endDate) {
        $errors[] = 'End date must be after start date.';
    }
    
    if ($registrationDeadline && $startDate && $registrationDeadline > $startDate) {
        $errors[] = 'Registration deadline must be before start date.';
    }
    
    // Validate fee amount
    $feeAmount = $_POST['fee_amount'] ?? '';
    if ($feeAmount !== '' && (!is_numeric($feeAmount) || $feeAmount < 0)) {
        $errors[] = 'Fee amount must be a non-negative number.';
    }
    
    // Validate max participants
    $maxParticipants = $_POST['max_participants'] ?? '';
    if ($maxParticipants !== '' && (!is_numeric($maxParticipants) || $maxParticipants <= 0)) {
        $errors[] = 'Maximum participants must be a positive number.';
    }
    
    // Validate circuit access
    $circuitId = $_POST['circuit_id'] ?? '';
    
    if (!$isAdmin) {
        // Non-admin users can only create conferences for their own circuit
        if ($userCircuit && $circuitId != $userCircuit['id']) {
            $errors[] = 'You can only create conferences for your own circuit.';
        }
    }
    
    // If no errors, insert the conference
    if (empty($errors)) {
        $name = mysqli_real_escape_string($conn, $_POST['name']);
        $description = mysqli_real_escape_string($conn, $_POST['description']);
        $startDate = mysqli_real_escape_string($conn, $_POST['start_date']);
        $endDate = mysqli_real_escape_string($conn, $_POST['end_date']);
        $registrationDeadline = mysqli_real_escape_string($conn, $_POST['registration_deadline']);
        $venue = mysqli_real_escape_string($conn, $_POST['venue']);
        $feeAmount = (float) $_POST['fee_amount'];
        $maxParticipants = !empty($_POST['max_participants']) ? (int) $_POST['max_participants'] : 'NULL';
        $circuitId = (int) $_POST['circuit_id'];
        
        $query = "INSERT INTO conferences (
                    name, description, start_date, end_date, registration_deadline, 
                    venue, type, entity_id, fee_amount, max_participants, status, created_by
                ) VALUES (
                    '$name', '$description', '$startDate', '$endDate', '$registrationDeadline',
                    '$venue', 'circuit', $circuitId, $feeAmount, $maxParticipants, 'upcoming', {$_SESSION['user_id']}
                )";
        
        if (mysqli_query($conn, $query)) {
            $conferenceId = mysqli_insert_id($conn);
            $successMessage = "Circuit conference created successfully!";
            
            // Redirect to add sessions page
            header("Location: circuit_sessions.php?conference_id=$conferenceId");
            exit;
        } else {
            $errorMessage = "Error creating conference: " . mysqli_error($conn);
        }
    } else {
        $errorMessage = implode("<br>", $errors);
    }
}

// Page title
$pageTitle = "Circuit Conference Setup";

?>

<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">Circuit Conference Setup</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a href="index.php" class="btn btn-sm btn-secondary">
                            <i class="fas fa-arrow-left me-1"></i> Back to Conferences
                        </a>
                    </div>
                </div>
                
                <?php if ($successMessage): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <?php echo $successMessage; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php endif; ?>
                
                <?php if ($errorMessage): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <?php echo $errorMessage; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php endif; ?>
                
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Circuit Conference Details</h6>
                    </div>
                    <div class="card-body">
                        <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label for="name" class="form-label">Conference Name <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="name" name="name" value="<?php echo $_POST['name'] ?? ''; ?>" required>
                                </div>
                                <div class="col-md-6">
                                    <label for="circuit_id" class="form-label">Circuit <span class="text-danger">*</span></label>
                                    <select class="form-select" id="circuit_id" name="circuit_id" required>
                                        <option value="">Select Circuit</option>
                                        <?php foreach ($circuits as $circuit): ?>
                                        <option value="<?php echo $circuit['id']; ?>" <?php echo (isset($_POST['circuit_id']) && $_POST['circuit_id'] == $circuit['id']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($circuit['name'] . ' (' . $circuit['diocese_name'] . ')'); ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="description" class="form-label">Description <span class="text-danger">*</span></label>
                                <textarea class="form-control" id="description" name="description" rows="3" required><?php echo $_POST['description'] ?? ''; ?></textarea>
                            </div>
                            
                            <div class="row mb-3">
                                <div class="col-md-4">
                                    <label for="start_date" class="form-label">Start Date <span class="text-danger">*</span></label>
                                    <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo $_POST['start_date'] ?? ''; ?>" required>
                                </div>
                                <div class="col-md-4">
                                    <label for="end_date" class="form-label">End Date <span class="text-danger">*</span></label>
                                    <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo $_POST['end_date'] ?? ''; ?>" required>
                                </div>
                                <div class="col-md-4">
                                    <label for="registration_deadline" class="form-label">Registration Deadline <span class="text-danger">*</span></label>
                                    <input type="date" class="form-control" id="registration_deadline" name="registration_deadline" value="<?php echo $_POST['registration_deadline'] ?? ''; ?>" required>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="venue" class="form-label">Venue <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="venue" name="venue" value="<?php echo $_POST['venue'] ?? ''; ?>" required>
                            </div>
                            
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label for="fee_amount" class="form-label">Registration Fee <span class="text-danger">*</span></label>
                                    <div class="input-group">
                                        <span class="input-group-text">GH₵</span>
                                        <input type="number" class="form-control" id="fee_amount" name="fee_amount" min="0" step="0.01" value="<?php echo $_POST['fee_amount'] ?? '0.00'; ?>" required>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <label for="max_participants" class="form-label">Maximum Participants</label>
                                    <input type="number" class="form-control" id="max_participants" name="max_participants" min="1" value="<?php echo $_POST['max_participants'] ?? ''; ?>">
                                    <div class="form-text">Leave blank for unlimited participants</div>
                                </div>
                            </div>
                            
                            <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save me-1"></i> Create Circuit Conference
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </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() {
        // Date validation
        $('#start_date, #end_date, #registration_deadline').change(function() {
            const startDate = $('#start_date').val();
            const endDate = $('#end_date').val();
            const regDeadline = $('#registration_deadline').val();
            
            if (startDate && endDate && startDate > endDate) {
                alert('End date must be after start date.');
                $('#end_date').val('');
            }
            
            if (regDeadline && startDate && regDeadline > startDate) {
                alert('Registration deadline must be before start date.');
                $('#registration_deadline').val('');
            }
        });
    });
    </script>
</body>
</html>
