<?php
// Include required files
require_once '../includes/auth.php';
require_once '../config/database.php';

// Require login
requireLogin();

// Basic variables
$pageTitle = "Diocese Conference Sessions";
$userId = $_SESSION['user_id'];
$isAdmin = hasRole(['admin']);
$isDiocesanRole = hasRole(['diocesan_chairman', 'diocesan_secretary', 'diocesan_music_director', 'diocesan_dom', 'diocesan_treasurer']);

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

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

// Get conference ID from URL
$conferenceId = isset($_GET['conference_id']) ? (int)$_GET['conference_id'] : 0;
$conference = null;
$sessions = [];

// If conference ID provided, get conference details
if ($conferenceId) {
    $conference = fetchRow("SELECT c.*, d.name as diocese_name 
                        FROM conferences c
                        JOIN dioceses d ON c.entity_id = d.id
                        WHERE c.id = $conferenceId AND c.type = 'diocese'");

    if (!$conference) {
        $conferenceError = "Conference not found or not a diocese conference";
    } else {
        // Get sessions for this conference
        $sessions = fetchRows("SELECT * FROM conference_sessions 
                              WHERE conference_id = $conferenceId 
                              ORDER BY start_time");
    }
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$accessDenied && $conferenceId) {
    $action = isset($_POST['action']) ? $_POST['action'] : '';
    
    if ($action === 'add_session') {
        // Validate inputs
        $name = isset($_POST['name']) ? trim($_POST['name']) : '';
        $description = isset($_POST['description']) ? trim($_POST['description']) : '';
        $startTime = isset($_POST['start_time']) ? trim($_POST['start_time']) : '';
        $endTime = isset($_POST['end_time']) ? trim($_POST['end_time']) : '';
        $venue = isset($_POST['venue']) ? trim($_POST['venue']) : '';
        $facilitator = isset($_POST['facilitator']) ? trim($_POST['facilitator']) : '';
        
        // Basic validation
        if (empty($name) || empty($startTime) || empty($endTime)) {
            $errorMessage = "Session name, start time, and end time are required";
        } else {
            // Insert new session
            $query = "INSERT INTO conference_sessions 
                     (conference_id, name, description, start_time, end_time, venue, facilitator, created_by) 
                     VALUES ($conferenceId, '$name', '$description', '$startTime', '$endTime', '$venue', '$facilitator', $userId)";
            
            if (executeQuery($query)) {
                $successMessage = "Session added successfully";
                // Refresh sessions list
                $sessions = fetchRows("SELECT * FROM conference_sessions 
                                      WHERE conference_id = $conferenceId 
                                      ORDER BY start_time");
            } else {
                $errorMessage = "Failed to add session. Please try again.";
            }
        }
    } elseif ($action === 'delete_session') {
        $sessionId = isset($_POST['session_id']) ? (int)$_POST['session_id'] : 0;
        
        if ($sessionId) {
            // Check if session exists and belongs to this conference
            $sessionCheck = fetchRow("SELECT id FROM conference_sessions 
                                    WHERE id = $sessionId AND conference_id = $conferenceId");
            
            if ($sessionCheck) {
                // Delete session
                if (executeQuery("DELETE FROM conference_sessions WHERE id = $sessionId")) {
                    $successMessage = "Session deleted successfully";
                    // Refresh sessions list
                    $sessions = fetchRows("SELECT * FROM conference_sessions 
                                          WHERE conference_id = $conferenceId 
                                          ORDER BY start_time");
                } else {
                    $errorMessage = "Failed to delete session. Please try again.";
                }
            } else {
                $errorMessage = "Invalid session selected";
            }
        } else {
            $errorMessage = "No session selected for deletion";
        }
    } elseif ($action === 'edit_session') {
        $sessionId = isset($_POST['session_id']) ? (int)$_POST['session_id'] : 0;
        $name = isset($_POST['name']) ? trim($_POST['name']) : '';
        $description = isset($_POST['description']) ? trim($_POST['description']) : '';
        $startTime = isset($_POST['start_time']) ? trim($_POST['start_time']) : '';
        $endTime = isset($_POST['end_time']) ? trim($_POST['end_time']) : '';
        $venue = isset($_POST['venue']) ? trim($_POST['venue']) : '';
        $facilitator = isset($_POST['facilitator']) ? trim($_POST['facilitator']) : '';
        
        // Basic validation
        if (empty($sessionId) || empty($name) || empty($startTime) || empty($endTime)) {
            $errorMessage = "Session ID, name, start time, and end time are required";
        } else {
            // Check if session exists and belongs to this conference
            $sessionCheck = fetchRow("SELECT id FROM conference_sessions 
                                    WHERE id = $sessionId AND conference_id = $conferenceId");
            
            if ($sessionCheck) {
                // Update session
                $query = "UPDATE conference_sessions SET 
                         name = '$name', 
                         description = '$description', 
                         start_time = '$startTime', 
                         end_time = '$endTime', 
                         venue = '$venue', 
                         facilitator = '$facilitator',
                         updated_at = CURRENT_TIMESTAMP
                         WHERE id = $sessionId";
                
                if (executeQuery($query)) {
                    $successMessage = "Session updated successfully";
                    // Refresh sessions list
                    $sessions = fetchRows("SELECT * FROM conference_sessions 
                                          WHERE conference_id = $conferenceId 
                                          ORDER BY start_time");
                } else {
                    $errorMessage = "Failed to update session. Please try again.";
                }
            } else {
                $errorMessage = "Invalid session selected";
            }
        }
    }
}

// Update page title if conference is found
if ($conference) {
    $pageTitle = "Manage Sessions: " . htmlspecialchars($conference['name']);
}
?>
<!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>
    
    <?php include '../includes/favicon.php'; ?>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->


</head>
<body>
    <?php include '../includes/navbar.php'; ?>
    
    <div class="container-fluid">
        <div class="row">
            <?php include '../includes/sidebar.php'; ?>
            
            <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">Manage Conference Sessions</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a href="index.php" class="btn btn-sm btn-secondary me-2">
                            <i class="fas fa-arrow-left"></i> Back to Conferences
                        </a>
                    </div>
                </div>
                
                <?php if ($accessDenied): ?>
                <div class="alert alert-danger">
                    <?php echo $accessError; ?>
                </div>
                <?php elseif ($conferenceError): ?>
                <div class="alert alert-danger">
                    <?php echo $conferenceError; ?>
                </div>
                <?php elseif ($conference): ?>
                    <?php if ($successMessage): ?>
                    <div class="alert alert-success">
                        <?php echo $successMessage; ?>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($errorMessage): ?>
                    <div class="alert alert-danger">
                        <?php echo $errorMessage; ?>
                    </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">
                            <div class="row">
                                <div class="col-md-6">
                                    <p><strong>Conference:</strong> <?php echo htmlspecialchars($conference['name']); ?></p>
                                    <p><strong>Diocese:</strong> <?php echo htmlspecialchars($conference['diocese_name']); ?></p>
                                </div>
                                <div class="col-md-6">
                                    <p><strong>Dates:</strong> <?php echo date('M d, Y', strtotime($conference['start_date'])); ?> - 
                                        <?php echo date('M d, Y', strtotime($conference['end_date'])); ?></p>
                                    <p><strong>Venue:</strong> <?php echo htmlspecialchars($conference['venue']); ?></p>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-5">
                            <div class="card shadow mb-4">
                                <div class="card-header py-3">
                                    <h6 class="m-0 font-weight-bold text-primary">Add Conference Session</h6>
                                </div>
                                <div class="card-body">
                                    <form method="post" action="">
                                        <input type="hidden" name="action" value="add_session">
                                        <input type="hidden" name="conference_id" value="<?php echo $conferenceId; ?>">
                                        
                                        <div class="mb-3">
                                            <label for="name" class="form-label">Session Name*</label>
                                            <input type="text" class="form-control" id="name" name="name" required>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="description" class="form-label">Description</label>
                                            <textarea class="form-control" id="description" name="description" rows="3"></textarea>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label for="start_time" class="form-label">Start Time*</label>
                                                    <input type="text" class="form-control datetime-picker" id="start_time" name="start_time" required>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label for="end_time" class="form-label">End Time*</label>
                                                    <input type="text" class="form-control datetime-picker" id="end_time" name="end_time" required>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="venue" class="form-label">Venue</label>
                                            <input type="text" class="form-control" id="venue" name="venue">
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="facilitator" class="form-label">Facilitator</label>
                                            <input type="text" class="form-control" id="facilitator" name="facilitator">
                                        </div>
                                        
                                        <button type="submit" class="btn btn-primary">Add Session</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-7">
                            <div class="card shadow mb-4">
                                <div class="card-header py-3">
                                    <h6 class="m-0 font-weight-bold text-primary">Conference Sessions</h6>
                                </div>
                                <div class="card-body">
                                    <?php if (count($sessions) > 0): ?>
                                    <div class="table-responsive">
                                        <table class="table table-bordered" id="sessionsTable" width="100%" cellspacing="0">
                                            <thead>
                                                <tr>
                                                    <th>Name</th>
                                                    <th>Date & Time</th>
                                                    <th>Venue</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($sessions as $session): ?>
                                                <tr>
                                                    <td>
                                                        <?php echo htmlspecialchars($session['name']); ?>
                                                        <?php if (!empty($session['facilitator'])): ?>
                                                        <br><small class="text-muted">Facilitator: <?php echo htmlspecialchars($session['facilitator']); ?></small>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <?php echo date('M d, Y h:i A', strtotime($session['start_time'])); ?> - 
                                                        <?php echo date('h:i A', strtotime($session['end_time'])); ?>
                                                    </td>
                                                    <td><?php echo htmlspecialchars($session['venue']); ?></td>
                                                    <td>
                                                        <button type="button" class="btn btn-sm btn-primary edit-session-btn" 
                                                                data-id="<?php echo $session['id']; ?>"
                                                                data-name="<?php echo htmlspecialchars($session['name']); ?>"
                                                                data-description="<?php echo htmlspecialchars($session['description']); ?>"
                                                                data-start="<?php echo $session['start_time']; ?>"
                                                                data-end="<?php echo $session['end_time']; ?>"
                                                                data-venue="<?php echo htmlspecialchars($session['venue']); ?>"
                                                                data-facilitator="<?php echo htmlspecialchars($session['facilitator']); ?>">
                                                            <i class="fas fa-edit"></i>
                                                        </button>
                                                        <form method="post" action="" class="d-inline delete-form">
                                                            <input type="hidden" name="action" value="delete_session">
                                                            <input type="hidden" name="session_id" value="<?php echo $session['id']; ?>">
                                                            <button type="submit" class="btn btn-sm btn-danger delete-btn">
                                                                <i class="fas fa-trash"></i>
                                                            </button>
                                                        </form>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    <?php else: ?>
                                    <p>No sessions have been added yet.</p>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Edit Session Modal -->
                    <div class="modal fade" id="editSessionModal" tabindex="-1" aria-labelledby="editSessionModalLabel" aria-hidden="true">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="editSessionModalLabel">Edit Session</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                </div>
                                <form method="post" action="">
                                    <div class="modal-body">
                                        <input type="hidden" name="action" value="edit_session">
                                        <input type="hidden" name="session_id" id="edit_session_id">
                                        
                                        <div class="mb-3">
                                            <label for="edit_name" class="form-label">Session Name*</label>
                                            <input type="text" class="form-control" id="edit_name" name="name" required>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="edit_description" class="form-label">Description</label>
                                            <textarea class="form-control" id="edit_description" name="description" rows="3"></textarea>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label for="edit_start_time" class="form-label">Start Time*</label>
                                                    <input type="text" class="form-control datetime-picker" id="edit_start_time" name="start_time" required>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label for="edit_end_time" class="form-label">End Time*</label>
                                                    <input type="text" class="form-control datetime-picker" id="edit_end_time" name="end_time" required>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="edit_venue" class="form-label">Venue</label>
                                            <input type="text" class="form-control" id="edit_venue" name="venue">
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="edit_facilitator" class="form-label">Facilitator</label>
                                            <input type="text" class="form-control" id="edit_facilitator" name="facilitator">
                                        </div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                        <button type="submit" class="btn btn-primary">Save Changes</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="card shadow mb-4">
                        <div class="card-body">
                            <h5>Available Diocese Conferences</h5>
                            <?php
                            $availableConferences = fetchRows("SELECT c.*, d.name as diocese_name 
                                                            FROM conferences c
                                                            JOIN dioceses d ON c.entity_id = d.id
                                                            WHERE c.type = 'diocese'
                                                            ORDER BY c.start_date DESC");
                            
                            if ($availableConferences): ?>
                            <div class="table-responsive">
                                <table class="table table-bordered">
                                    <thead>
                                        <tr>
                                            <th>Name</th>
                                            <th>Diocese</th>
                                            <th>Date</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($availableConferences as $conf): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($conf['name']); ?></td>
                                            <td><?php echo htmlspecialchars($conf['diocese_name']); ?></td>
                                            <td><?php echo date('M d, Y', strtotime($conf['start_date'])); ?> - 
                                                <?php echo date('M d, Y', strtotime($conf['end_date'])); ?></td>
                                            <td>
                                                <a href="diocese_sessions.php?conference_id=<?php echo $conf['id']; ?>" 
                                                   class="btn btn-sm btn-primary">
                                                    Manage Sessions
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            <?php else: ?>
                            <p>No diocese conferences found.</p>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endif; ?>
            </main>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    
    <script>
    $(document).ready(function() {
        // Initialize datetime pickers
        $(".datetime-picker").flatpickr({
            enableTime: true,
            dateFormat: "Y-m-d H:i",
            time_24hr: true
        });
        
        // Handle edit session button click
        $('.edit-session-btn').click(function() {
            const id = $(this).data('id');
            const name = $(this).data('name');
            const description = $(this).data('description');
            const start = $(this).data('start');
            const end = $(this).data('end');
            const venue = $(this).data('venue');
            const facilitator = $(this).data('facilitator');
            
            $('#edit_session_id').val(id);
            $('#edit_name').val(name);
            $('#edit_description').val(description);
            $('#edit_venue').val(venue);
            $('#edit_facilitator').val(facilitator);
            
            // Set datetime values using flatpickr
            $('#edit_start_time').val(start);
            $('#edit_end_time').val(end);
            
            // Initialize modal datetime pickers
            $("#edit_start_time").flatpickr({
                enableTime: true,
                dateFormat: "Y-m-d H:i",
                time_24hr: true,
                defaultDate: start
            });
            
            $("#edit_end_time").flatpickr({
                enableTime: true,
                dateFormat: "Y-m-d H:i",
                time_24hr: true,
                defaultDate: end
            });
            
            $('#editSessionModal').modal('show');
        });
        
        // Confirm delete
        $('.delete-form').submit(function(e) {
            if (!confirm('Are you sure you want to delete this session?')) {
                e.preventDefault();
            }
        });
    });
    </script>
</body>
</html>
