<?php
/**
 * Create Conference
 * GHAMECC Choir Management Platform
 * 
 * This page allows authorized users to create new conferences.
 */

// Include database connection and functions
require_once '../config/database.php';

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

// Require login
requireLogin();

// Check if user has appropriate permissions
if (!hasRole(['admin']) && 
    !fetchRow("SELECT * FROM circuit_roles WHERE user_id = {$_SESSION['user_id']} AND role IN ('chairman', 'secretary')") &&
    !fetchRow("SELECT * FROM diocese_roles WHERE user_id = {$_SESSION['user_id']} AND role IN ('chairman', 'secretary')")) {
    header("Location: ../index.php");
    exit("Unauthorized access");
}

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

// Get user's roles and associated entities
$userId = $_SESSION['user_id'];
$userCircuits = [];
$userDioceses = [];
$isAdmin = hasRole(['admin']);

// Get user's circuit roles
$circuitRoles = fetchRows("SELECT cr.circuit_id, c.name 
                          FROM circuit_roles cr 
                          JOIN circuits c ON cr.circuit_id = c.id 
                          WHERE cr.user_id = $userId AND cr.role IN ('chairman', 'secretary')");
if ($circuitRoles) {
    foreach ($circuitRoles as $role) {
        $userCircuits[$role['circuit_id']] = $role['name'];
    }
}

// Get user's diocese roles
$dioceseRoles = fetchRows("SELECT dr.diocese_id, d.name 
                          FROM diocese_roles dr 
                          JOIN dioceses d ON dr.diocese_id = d.id 
                          WHERE dr.user_id = $userId AND dr.role IN ('chairman', 'secretary')");
if ($dioceseRoles) {
    foreach ($dioceseRoles as $role) {
        $userDioceses[$role['diocese_id']] = $role['name'];
    }
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate inputs
    $errors = [];
    
    // Required fields
    $requiredFields = ['name', 'description', 'start_date', 'end_date', 'registration_deadline', 'venue', 'type', 'entity_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 entity access
    $type = $_POST['type'] ?? '';
    $entityId = $_POST['entity_id'] ?? '';
    
    if ($type && $entityId) {
        $hasAccess = false;
        
        if ($isAdmin) {
            $hasAccess = true;
        } else if ($type === 'circuit' && isset($userCircuits[$entityId])) {
            $hasAccess = true;
        } else if ($type === 'diocese' && isset($userDioceses[$entityId])) {
            $hasAccess = true;
        }
        
        if (!$hasAccess) {
            $errors[] = 'You do not have permission to create a conference for this ' . $type . '.';
        }
    }
    
    // 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']);
        $type = mysqli_real_escape_string($conn, $_POST['type']);
        $entityId = (int)$_POST['entity_id'];
        $feeAmount = (float)$_POST['fee_amount'];
        $maxParticipants = !empty($_POST['max_participants']) ? (int)$_POST['max_participants'] : 'NULL';
        $status = mysqli_real_escape_string($conn, $_POST['status'] ?? 'upcoming');
        
        $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', '$type', $entityId, $feeAmount, $maxParticipants, '$status', $userId)";
        
        $result = executeQuery($query);
        
        if ($result) {
            $conferenceId = mysqli_insert_id($conn);
            header("Location: view.php?id=$conferenceId&created=1");
            exit;
        } else {
            $errors[] = 'Error creating conference: ' . mysqli_error($conn);
        }
    }
}

// Get all circuits and dioceses for dropdown (admin only sees all)
$circuits = [];
$dioceses = [];

if ($isAdmin) {
    $circuits = fetchRows("SELECT id, name FROM circuits ORDER BY name");
    $dioceses = fetchRows("SELECT id, name FROM dioceses ORDER BY name");
} else {
    // Only show circuits and dioceses the user has access to
    if (!empty($userCircuits)) {
        $circuitIds = array_keys($userCircuits);
        $circuitIdsStr = implode(',', $circuitIds);
        $circuits = fetchRows("SELECT id, name FROM circuits WHERE id IN ($circuitIdsStr) ORDER BY name");
    }
    
    if (!empty($userDioceses)) {
        $dioceseIds = array_keys($userDioceses);
        $dioceseIdsStr = implode(',', $dioceseIds);
        $dioceses = fetchRows("SELECT id, name FROM dioceses WHERE id IN ($dioceseIdsStr) ORDER BY name");
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Conference - GHAMECC Choir Management</title>
    
    <?php include '../includes/favicon.php'; ?>
    
    <!-- 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">
    <!-- Flatpickr CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.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">Create New Conference</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 (!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 $error; ?></li>
                            <?php endforeach; ?>
                        </ul>
                        <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">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="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>
                            
                            <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 datepicker" 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 datepicker" 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 datepicker" id="registration_deadline" name="registration_deadline" value="<?php echo $_POST['registration_deadline'] ?? ''; ?>" required>
                                </div>
                            </div>
                            
                            <div class="row mb-3">
                                <div class="col-md-4">
                                    <label for="type" class="form-label">Conference Type <span class="text-danger">*</span></label>
                                    <select class="form-select" id="type" name="type" required>
                                        <option value="">Select Type</option>
                                        <option value="circuit" <?php echo (isset($_POST['type']) && $_POST['type'] === 'circuit') ? 'selected' : ''; ?>>Circuit</option>
                                        <option value="diocese" <?php echo (isset($_POST['type']) && $_POST['type'] === 'diocese') ? 'selected' : ''; ?>>Diocese</option>
                                        <?php if ($isAdmin): ?>
                                            <option value="connexional" <?php echo (isset($_POST['type']) && $_POST['type'] === 'connexional') ? 'selected' : ''; ?>>Connexional</option>
                                        <?php endif; ?>
                                    </select>
                                </div>
                                <div class="col-md-8">
                                    <label for="entity_id" class="form-label">Entity <span class="text-danger">*</span></label>
                                    <select class="form-select" id="entity_id" name="entity_id" required>
                                        <option value="">Select Entity</option>
                                        <!-- Options will be populated via JavaScript -->
                                    </select>
                                </div>
                            </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="mb-3">
                                <label for="status" class="form-label">Status</label>
                                <select class="form-select" id="status" name="status">
                                    <option value="upcoming" <?php echo (!isset($_POST['status']) || $_POST['status'] === 'upcoming') ? 'selected' : ''; ?>>Upcoming</option>
                                    <option value="ongoing" <?php echo (isset($_POST['status']) && $_POST['status'] === 'ongoing') ? 'selected' : ''; ?>>Ongoing</option>
                                    <option value="completed" <?php echo (isset($_POST['status']) && $_POST['status'] === 'completed') ? 'selected' : ''; ?>>Completed</option>
                                    <option value="cancelled" <?php echo (isset($_POST['status']) && $_POST['status'] === 'cancelled') ? 'selected' : ''; ?>>Cancelled</option>
                                </select>
                            </div>
                            
                            <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                <button type="reset" class="btn btn-secondary me-md-2">Reset</button>
                                <button type="submit" class="btn btn-primary">Create 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>
    <!-- Flatpickr JS -->
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    
    <script>
        // Store entities data
        const circuits = <?php echo json_encode($circuits); ?>;
        const dioceses = <?php echo json_encode($dioceses); ?>;
        
        // Function to populate entity dropdown based on selected type
        function populateEntityDropdown() {
            const typeSelect = document.getElementById('type');
            const entitySelect = document.getElementById('entity_id');
            const selectedType = typeSelect.value;
            const selectedEntityId = '<?php echo $_POST['entity_id'] ?? ''; ?>';
            
            // Clear existing options
            entitySelect.innerHTML = '<option value="">Select Entity</option>';
            
            if (selectedType === 'circuit') {
                circuits.forEach(circuit => {
                    const option = document.createElement('option');
                    option.value = circuit.id;
                    option.textContent = circuit.name;
                    if (selectedEntityId === circuit.id) {
                        option.selected = true;
                    }
                    entitySelect.appendChild(option);
                });
            } else if (selectedType === 'diocese') {
                dioceses.forEach(diocese => {
                    const option = document.createElement('option');
                    option.value = diocese.id;
                    option.textContent = diocese.name;
                    if (selectedEntityId === diocese.id) {
                        option.selected = true;
                    }
                    entitySelect.appendChild(option);
                });
            } else if (selectedType === 'connexional') {
                const option = document.createElement('option');
                option.value = '0';
                option.textContent = 'Connexional Office';
                entitySelect.appendChild(option);
                entitySelect.value = '0';
            }
        }
        
        // Initialize date pickers
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize flatpickr for date inputs
            flatpickr(".datepicker", {
                dateFormat: "Y-m-d",
                allowInput: true
            });
            
            // Set up entity dropdown change handler
            document.getElementById('type').addEventListener('change', populateEntityDropdown);
            
            // Initial population
            populateEntityDropdown();
        });
    </script>
</body>
</html>
