<?php
/**
 * Conference Room Check-In/Check-Out Management
 * GHAMECC Choir Management Platform
 * 
 * This page allows administrators to check in and check out delegates from their assigned rooms
 * for conference events.
 */

require_once '../includes/auth.php';
require_once '../config/database.php';

// Require login
requireLogin();

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

// Basic variables
$pageTitle = "Room Check-In/Check-Out";
$userId = $_SESSION['user_id'];
$isDioceseRole = hasRole(['diocesan_chairman', 'diocesan_secretary', 'diocesan_treasurer', 'diocesan_dom']);

// Check if user has appropriate permissions (only diocese roles)
if (!hasRole(['diocesan_chairman', 'diocesan_secretary', 'diocesan_treasurer', 'diocesan_dom'])) {
    header("Location: ../index.php");
    exit("Unauthorized access");
}

// Get user's diocese
$userDioceseId = 0;
if ($isDioceseRole) {
    $userDioceseQuery = "SELECT diocese_id FROM users WHERE id = $userId";
    $userDioceseResult = fetchRow($userDioceseQuery);
    if ($userDioceseResult && isset($userDioceseResult['diocese_id'])) {
        $userDioceseId = $userDioceseResult['diocese_id'];
    }
}

// If no diocese ID found, redirect to index
if (!$userDioceseId) {
    header("Location: ../index.php");
    exit("No diocese assigned to your account");
}

// Get assignment ID from URL
$assignmentId = isset($_GET['assignment_id']) ? (int)$_GET['assignment_id'] : 0;

// If no assignment ID provided, redirect back to room assignments
if (!$assignmentId) {
    // Just redirect back to the referring page or index
    header("Location: " . ($_SERVER['HTTP_REFERER'] ?? 'index.php'));
    exit("No assignment selected");
}

// Get assignment details
$assignmentQuery = "SELECT cra.*, cr.conference_id, 
                   m.first_name, m.last_name, m.gender,
                   s.name as society_name, c.name as circuit_name,
                   cat.name as accommodation_type_name
                   FROM conference_room_assignments cra
                   JOIN conference_registrations cr ON cra.registration_id = cr.id
                   JOIN members m ON cr.member_id = m.id
                   JOIN societies s ON m.society_id = s.id
                   JOIN circuits c ON s.circuit_id = c.id
                   JOIN conference_accommodation_types cat ON cra.accommodation_type_id = cat.id
                   WHERE cra.id = $assignmentId";
$assignment = fetchRow($assignmentQuery);

// If assignment not found, redirect back
if (!$assignment) {
    // Just redirect back to the referring page or index
    header("Location: " . ($_SERVER['HTTP_REFERER'] ?? 'index.php'));
    exit("Assignment not found");
}

// Get conference details
$conferenceId = $assignment['conference_id'];
$conference = fetchRow("SELECT c.*, d.name as diocese_name
                       FROM conferences c
                       LEFT JOIN dioceses d ON (c.entity_id = d.id AND c.type = 'diocese')
                       WHERE c.id = $conferenceId AND c.type = 'diocese'");

// If conference not found, redirect
if (!$conference) {
    header("Location: index.php");
    exit("Conference not found or not a diocese conference");
}

// Check if diocese has access to this conference
$hasAccess = false;

// For diocese conferences, check if user belongs to the conference's diocese
if ($userDioceseId == $conference['entity_id']) {
    $hasAccess = true;
}

// Redirect if no access
if (!$hasAccess) {
    header("Location: index.php");
    exit("You don't have access to this conference");
}

// Process form submissions
$message = '';
$messageType = '';

// Handle check-in
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['check_in'])) {
    // Update check-in date
    $updateQuery = "UPDATE conference_room_assignments 
                   SET check_in_date = NOW(), updated_by = $userId 
                   WHERE id = $assignmentId";
    
    if (mysqli_query($conn, $updateQuery)) {
        $message = "Delegate successfully checked in.";
        $messageType = "success";
        
        // Refresh assignment data
        $assignment = fetchRow($assignmentQuery);
    } else {
        $message = "Error checking in: " . mysqli_error($conn);
        $messageType = "danger";
    }
}

// Handle check-out
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['check_out'])) {
    // Update check-out date
    $updateQuery = "UPDATE conference_room_assignments 
                   SET check_out_date = NOW(), updated_by = $userId 
                   WHERE id = $assignmentId";
    
    if (mysqli_query($conn, $updateQuery)) {
        $message = "Delegate successfully checked out.";
        $messageType = "success";
        
        // Refresh assignment data
        $assignment = fetchRow($assignmentQuery);
    } else {
        $message = "Error checking out: " . mysqli_error($conn);
        $messageType = "danger";
    }
}

// Handle notes update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_notes'])) {
    $notes = isset($_POST['notes']) ? mysqli_real_escape_string($conn, trim($_POST['notes'])) : '';
    
    // Update notes
    $updateQuery = "UPDATE conference_room_assignments 
                   SET notes = '$notes', updated_by = $userId 
                   WHERE id = $assignmentId";
    
    if (mysqli_query($conn, $updateQuery)) {
        $message = "Notes successfully updated.";
        $messageType = "success";
        
        // Refresh assignment data
        $assignment = fetchRow($assignmentQuery);
    } else {
        $message = "Error updating notes: " . mysqli_error($conn);
        $messageType = "danger";
    }
}

// Format dates for display
$checkInDate = $assignment['check_in_date'] ? date('M d, Y h:i A', strtotime($assignment['check_in_date'])) : 'Not checked in';
$checkOutDate = $assignment['check_out_date'] ? date('M d, Y h:i A', strtotime($assignment['check_out_date'])) : 'Not checked out';

// Determine status
$status = 'Not Checked In';
$statusClass = 'text-warning';

if ($assignment['check_in_date'] && !$assignment['check_out_date']) {
    $status = 'Checked In';
    $statusClass = 'text-success';
} else if ($assignment['check_in_date'] && $assignment['check_out_date']) {
    $status = 'Checked Out';
    $statusClass = 'text-danger';
}
?>

<!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 rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    
    <!-- Custom styles -->
    <link href="../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">Room Check-In/Check-Out</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a href="room_assignments.php" class="btn btn-sm btn-outline-secondary">
                            <i class="fas fa-arrow-left me-1"></i> Back to Room Assignments
                        </a>
                    </div>
                </div>
                
                <!-- Conference Info -->
                <div class="alert alert-info mb-4">
                    <strong>Conference:</strong> <?php echo htmlspecialchars($conference['name']); ?> | 
                    <strong>Diocese:</strong> <?php echo htmlspecialchars($conference['diocese_name']); ?> | 
                    <strong>Dates:</strong> <?php echo date('M d, Y', strtotime($conference['start_date'])); ?> - <?php echo date('M d, Y', strtotime($conference['end_date'])); ?>
                </div>
                
                <?php if ($message): ?>
                <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
                    <?php echo $message; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php endif; ?>
                
                <div class="row">
                    <div class="col-lg-12">
                        <div class="card shadow mb-4">
                            <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                                <h6 class="m-0 font-weight-bold text-primary">Delegate Room Assignment</h6>
                                <span class="badge bg-<?php echo $assignment['check_in_date'] ? ($assignment['check_out_date'] ? 'danger' : 'success') : 'warning'; ?>">
                                    <?php echo $status; ?>
                                </span>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <h5 class="mb-3">Delegate Information</h5>
                                        <table class="table table-bordered">
                                            <tr>
                                                <th width="30%">Name</th>
                                                <td><?php echo htmlspecialchars($assignment['first_name'] . ' ' . $assignment['last_name']); ?></td>
                                            </tr>
                                            <tr>
                                                <th>Gender</th>
                                                <td><?php echo htmlspecialchars($assignment['gender']); ?></td>
                                            </tr>
                                            <tr>
                                                <th>Society</th>
                                                <td><?php echo htmlspecialchars($assignment['society_name']); ?></td>
                                            </tr>
                                            <tr>
                                                <th>Circuit</th>
                                                <td><?php echo htmlspecialchars($assignment['circuit_name']); ?></td>
                                            </tr>
                                        </table>
                                    </div>
                                    <div class="col-md-6">
                                        <h5 class="mb-3">Accommodation Information</h5>
                                        <table class="table table-bordered">
                                            <tr>
                                                <th width="30%">Accommodation Type</th>
                                                <td><?php echo htmlspecialchars($assignment['accommodation_type_name']); ?></td>
                                            </tr>
                                            <tr>
                                                <th>Room Number</th>
                                                <td><?php echo htmlspecialchars($assignment['room_number']); ?></td>
                                            </tr>
                                            <tr>
                                                <th>Check-In</th>
                                                <td><?php echo $checkInDate; ?></td>
                                            </tr>
                                            <tr>
                                                <th>Check-Out</th>
                                                <td><?php echo $checkOutDate; ?></td>
                                            </tr>
                                        </table>
                                    </div>
                                </div>
                                
                                <div class="row mt-4">
                                    <div class="col-md-12">
                                        <h5 class="mb-3">Actions</h5>
                                        <div class="d-flex">
                                            <?php if (!$assignment['check_in_date']): ?>
                                            <form method="post" class="me-2">
                                                <button type="submit" name="check_in" class="btn btn-success">
                                                    <i class="fas fa-sign-in-alt me-1"></i> Check In
                                                </button>
                                            </form>
                                            <?php endif; ?>
                                            
                                            <?php if ($assignment['check_in_date'] && !$assignment['check_out_date']): ?>
                                            <form method="post" class="me-2">
                                                <button type="submit" name="check_out" class="btn btn-danger">
                                                    <i class="fas fa-sign-out-alt me-1"></i> Check Out
                                                </button>
                                            </form>
                                            <?php endif; ?>
                                            
                                            <?php if ($assignment['check_in_date'] && $assignment['check_out_date']): ?>
                                            <div class="alert alert-info mb-0">
                                                <i class="fas fa-info-circle me-1"></i> This delegate has completed their stay.
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="row mt-4">
                                    <div class="col-md-12">
                                        <h5 class="mb-3">Notes</h5>
                                        <form method="post">
                                            <div class="mb-3">
                                                <textarea name="notes" class="form-control" rows="4"><?php echo htmlspecialchars($assignment['notes'] ?? ''); ?></textarea>
                                            </div>
                                            <button type="submit" name="update_notes" class="btn btn-primary">
                                                <i class="fas fa-save me-1"></i> Update Notes
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </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>
</body>
</html>
