<?php
/**
 * Diocese Conference Setup
 * GHAMECC Choir Management Platform
 * 
 * This page allows diocese administrators to set up conferences for circuit delegates.
 */

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

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

// Require login
requireLogin();

// FIX: Set session role from database if it's empty
if (empty($_SESSION['role']) && isset($_SESSION['user_id'])) {
    $userId = $_SESSION['user_id'];
    $roleQuery = "SELECT r.role_key FROM users u JOIN roles r ON u.role_id = r.id WHERE u.id = $userId";
    $roleResult = fetchRow($roleQuery);
    
    if ($roleResult && isset($roleResult['role_key'])) {
        $_SESSION['role'] = $roleResult['role_key'];
        // Log the role fix
        echo "<div style='background: #d4edda; padding: 10px; margin: 10px; border: 1px solid #c3e6cb;'>";
        echo "<strong>Role Fix Applied:</strong> Session role was empty and has been set to: " . $_SESSION['role'];
        echo "</div>";
    }
}



// Get user's role from database
if (isset($_SESSION['user_id'])) {
    $userId = $_SESSION['user_id'];
    $userRoleQuery = "SELECT r.role_key, r.name, u.diocese_id 
                      FROM users u 
                      JOIN roles r ON u.role_id = r.id 
                      WHERE u.id = $userId";
    $userRoleResult = fetchRow($userRoleQuery);
    
 
}



// Check if user has appropriate permissions
$accessDenied = false;
$accessError = "";
$errorMessage = "";
$successMessage = "";
$noDioceseError = "";

if (!hasRole(['admin', 'diocesan_chairman', 'diocesan_secretary', 'diocesan_music_director', 'diocesan_treasurer'])) {
    $accessDenied = true;
    $accessError = "You don't have permission to access this page. This page is restricted to diocesan administrators.";
}

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

// Get user's diocese information
$userId = $_SESSION['user_id'];
$userDiocese = null;
$isAdmin = hasRole(['admin']);
$isDiocesanRole = hasRole(['diocesan_chairman', 'diocesan_secretary', 'diocesan_music_director',  'diocesan_treasurer']);

// If admin, they can manage any diocese
if ($isAdmin) {
    $dioceses = fetchRows("SELECT * FROM dioceses ORDER BY name");
} else {
    // Get user's diocese role
    $dioceseInfo = fetchRow("SELECT d.* 
                            FROM dioceses d
                            JOIN users u ON u.diocese_id = d.id
                            WHERE u.id = $userId");
    
    if ($dioceseInfo) {
        $userDiocese = $dioceseInfo;
        $dioceses = [$dioceseInfo];
    } else {
        // No diocese assigned - show error message instead of redirecting
        $noDioceseError = "No diocese assigned to your account. Please contact an administrator.";
        $dioceses = []; // Empty array to avoid errors
    }
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$accessDenied) {
    // Validate inputs
    $errors = [];
    
    // Required fields
    $requiredFields = ['name', 'description', 'start_date', 'end_date', 'registration_deadline', 'venue', 'diocese_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 diocese access
    $dioceseId = $_POST['diocese_id'] ?? '';
    
    if (!$isAdmin) {
        // Non-admin users can only create conferences for their own diocese
        if ($userDiocese && $dioceseId != $userDiocese['id']) {
            $errors[] = 'You can only create conferences for your own diocese.';
        }
    }
    
    // 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';
        $dioceseId = (int) $_POST['diocese_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', 'diocese', $dioceseId, $feeAmount, $maxParticipants, 'upcoming', {$_SESSION['user_id']}
                )";
        
        if (mysqli_query($conn, $query)) {
            $conferenceId = mysqli_insert_id($conn);
            $successMessage = "Diocese conference created successfully!";
            
            // Redirect to add sessions page
            header("Location: diocese_sessions.php?conference_id=$conferenceId");
            exit;
        } else {
            $errorMessage = "Error creating conference: " . mysqli_error($conn);
        }
    } else {
        $errorMessage = implode("<br>", $errors);
    }
}

// Page title
$pageTitle = "Diocese Conference Setup";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> | GHAMECC</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <!-- Custom styles -->
    <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">Diocese 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 ($accessDenied): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <?php echo $accessError; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php else: ?>
                    <?php if ($noDioceseError): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?php echo $noDioceseError; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php endif; ?>
                    
                    <?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">Diocese 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="diocese_id" class="form-label">Diocese <span class="text-danger">*</span></label>
                                        <select class="form-select" id="diocese_id" name="diocese_id" required>
                                            <option value="">Select Diocese</option>
                                            <?php foreach ($dioceses as $diocese): ?>
                                            <option value="<?php echo $diocese['id']; ?>" <?php echo (isset($_POST['diocese_id']) && $_POST['diocese_id'] == $diocese['id']) ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($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 Diocese Conference
                                    </button>
                                </div>
                            </form>
                        </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() {
        // 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>
