<?php
/**
 * Attendance Management
 * GHAMECC Choir Management Platform
 */

// Include necessary files
require_once '../includes/auth.php';
require_once '../config/database.php';

// Require login
requireLogin();

// Set page title
$pageTitle = "Attendance Management";
// Base path for includes used by sidebar/navbar
$basePath = '..';

// Get user role and entity IDs
$userRole = $_SESSION['role'] ?? '';
$userSocietyId = $_SESSION['society_id'] ?? null;
$userCircuitId = $_SESSION['circuit_id'] ?? null;
$userDioceseId = $_SESSION['diocese_id'] ?? null;

// Initialize variables
$societies = [];
$events = [];
$attendanceRecords = [];
$message = '';
$error = '';

// Process form submission for attendance recording
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['record_attendance'])) {
    $eventId = $_POST['event_id'] ?? '';
    $societyId = $_POST['society_id'] ?? '';
    $attendanceDate = $_POST['attendance_date'] ?? '';
    $memberAttendance = $_POST['member_attendance'] ?? [];
    
    // Validate input
    if (empty($eventId) || empty($societyId) || empty($attendanceDate) || empty($memberAttendance)) {
        $error = "Please fill all required fields.";
    } else {
        // Begin transaction
        $conn->begin_transaction();
        
        try {
            // Record attendance for each member
            foreach ($memberAttendance as $memberId => $status) {
                $query = "INSERT INTO attendance (member_id, event_id, society_id, attendance_date, status, recorded_by) 
                          VALUES (?, ?, ?, ?, ?, ?)
                          ON DUPLICATE KEY UPDATE status = ?, recorded_by = ?";
                
                $stmt = $conn->prepare($query);
                $stmt->bind_param("iiissisi", $memberId, $eventId, $societyId, $attendanceDate, $status, $_SESSION['user_id'], $status, $_SESSION['user_id']);
                $stmt->execute();
                $stmt->close();
            }
            
            // Commit transaction
            $conn->commit();
            $message = "Attendance recorded successfully.";
        } catch (Exception $e) {
            // Rollback transaction on error
            $conn->rollback();
            $error = "Error recording attendance: " . $e->getMessage();
        }
    }
}

// Get societies based on user role and access level
if ($userRole === 'admin') {
    // Admin can see all societies
    $query = "SELECT id, name FROM societies ORDER BY name";
    $stmt = $conn->prepare($query);
    $stmt->execute();
    $result = $stmt->get_result();
    $societies = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
} elseif ($userRole === 'diocesan_secretary' && !empty($userDioceseId)) {
    // Diocese secretary can see societies in their diocese
    $query = "SELECT s.id, s.name 
              FROM societies s 
              JOIN circuits c ON s.circuit_id = c.id 
              WHERE c.diocese_id = ? 
              ORDER BY s.name";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $userDioceseId);
    $stmt->execute();
    $result = $stmt->get_result();
    $societies = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
} elseif ($userRole === 'circuit_secretary' && !empty($userCircuitId)) {
    // Circuit secretary can see societies in their circuit
    $query = "SELECT id, name FROM societies WHERE circuit_id = ? ORDER BY name";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $userCircuitId);
    $stmt->execute();
    $result = $stmt->get_result();
    $societies = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
} elseif (!empty($userSocietyId)) {
    // Society users can only see their own society
    $query = "SELECT id, name FROM societies WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $userSocietyId);
    $stmt->execute();
    $result = $stmt->get_result();
    $societies = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
}

// Get events
$query = "SELECT id, name, event_date FROM events WHERE event_date >= CURDATE() - INTERVAL 30 DAY ORDER BY event_date DESC";
$stmt = $conn->prepare($query);
if ($stmt) {
    $stmt->execute();
    $result = $stmt->get_result();
    $events = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
    $stmt->close();
} else {
    if (function_exists('logError')) { logError("SQL Prepare Error", ['error' => $conn->error, 'query' => $query]); }
    $events = [];
}

// Get recent attendance records
$query = "SELECT a.id, a.attendance_date, e.name as event_name, s.name as society_name, 
          COUNT(CASE WHEN a.status = 'present' THEN 1 END) as present_count,
          COUNT(CASE WHEN a.status = 'absent' THEN 1 END) as absent_count,
          COUNT(CASE WHEN a.status = 'excused' THEN 1 END) as excused_count,
          COUNT(a.id) as total_count
          FROM attendance a
          JOIN events e ON a.event_id = e.id
          JOIN societies s ON a.society_id = s.id";

$whereParams = [];

// Add filters based on user role
if ($userRole === 'admin') {
    // No additional filters for admin
} elseif ($userRole === 'diocesan_secretary' && !empty($userDioceseId)) {
    $query .= " JOIN circuits c ON s.circuit_id = c.id WHERE c.diocese_id = ?";
    $whereParams[] = $userDioceseId;
} elseif ($userRole === 'circuit_secretary' && !empty($userCircuitId)) {
    $query .= " WHERE s.circuit_id = ?";
    $whereParams[] = $userCircuitId;
} elseif (!empty($userSocietyId)) {
    $query .= " WHERE a.society_id = ?";
    $whereParams[] = $userSocietyId;
}

$query .= " GROUP BY a.attendance_date, a.event_id, a.society_id
           ORDER BY a.attendance_date DESC
           LIMIT 10";

$stmt = $conn->prepare($query);
if ($stmt) {
    if (!empty($whereParams)) {
        $types = str_repeat("i", count($whereParams));
        $stmt->bind_param($types, ...$whereParams);
    }
    $stmt->execute();
    $result = $stmt->get_result();
    $attendanceRecords = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
    $stmt->close();
} else {
    if (function_exists('logError')) { logError("SQL Prepare Error", ['error' => $conn->error, 'query' => $query]); }
    $attendanceRecords = [];
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Attendance - 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">
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
    <!-- Custom CSS -->
    <link href="../assets/css/style.css" rel="stylesheet">
    <!-- Chart.js for statistics chart -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</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">
    <!-- Page Heading -->
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800"><?php echo $pageTitle; ?></h1>
    </div>

    <?php if (!empty($message)): ?>
        <div class="alert alert-success" role="alert">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>

    <?php if (!empty($error)): ?>
        <div class="alert alert-danger" role="alert">
            <?php echo $error; ?>
        </div>
    <?php endif; ?>

    <!-- Content Row -->
    <div class="row">
        <!-- Record Attendance Card -->
        <div class="col-xl-6 col-md-12 mb-4">
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Record Attendance</h6>
                </div>
                <div class="card-body">
                    <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
                        <div class="mb-3">
                            <label for="society_id" class="form-label">Society</label>
                            <select class="form-select" id="society_id" name="society_id" required>
                                <option value="">Select Society</option>
                                <?php foreach ($societies as $society): ?>
                                    <option value="<?php echo $society['id']; ?>">
                                        <?php echo htmlspecialchars($society['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label for="event_id" class="form-label">Event</label>
                            <select class="form-select" id="event_id" name="event_id" required>
                                <option value="">Select Event</option>
                                <?php foreach ($events as $event): ?>
                                    <option value="<?php echo $event['id']; ?>">
                                        <?php echo htmlspecialchars($event['name']); ?> 
                                        (<?php echo date('d M Y', strtotime($event['event_date'])); ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label for="attendance_date" class="form-label">Attendance Date</label>
                            <input type="date" class="form-control" id="attendance_date" name="attendance_date" 
                                   value="<?php echo date('Y-m-d'); ?>" required>
                        </div>

                        <div id="member-list" class="mb-3">
                            <p>Select a society to load members.</p>
                        </div>

                        <div class="d-grid gap-2">
                            <button type="submit" name="record_attendance" class="btn btn-primary">Record Attendance</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Recent Attendance Records Card -->
        <div class="col-xl-6 col-md-12 mb-4">
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Recent Attendance Records</h6>
                </div>
                <div class="card-body">
                    <?php if (empty($attendanceRecords)): ?>
                        <p>No attendance records found.</p>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-bordered" width="100%" cellspacing="0">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Event</th>
                                        <th>Society</th>
                                        <th>Present</th>
                                        <th>Absent</th>
                                        <th>Excused</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($attendanceRecords as $record): ?>
                                        <tr>
                                            <td><?php echo date('d M Y', strtotime($record['attendance_date'])); ?></td>
                                            <td><?php echo htmlspecialchars($record['event_name']); ?></td>
                                            <td><?php echo htmlspecialchars($record['society_name']); ?></td>
                                            <td><?php echo $record['present_count']; ?></td>
                                            <td><?php echo $record['absent_count']; ?></td>
                                            <td><?php echo $record['excused_count']; ?></td>
                                            <td>
                                                <a href="view.php?date=<?php echo $record['attendance_date']; ?>&event=<?php echo $record['event_id']; ?>&society=<?php echo $record['society_id']; ?>" 
                                                   class="btn btn-sm btn-info">
                                                    <i class="fas fa-eye"></i> View
                                                </a>
                                                <a href="edit.php?date=<?php echo $record['attendance_date']; ?>&event=<?php echo $record['event_id']; ?>&society=<?php echo $record['society_id']; ?>" 
                                                   class="btn btn-sm btn-warning">
                                                    <i class="fas fa-edit"></i> Edit
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Attendance Statistics Row -->
    <div class="row">
        <div class="col-xl-12 col-lg-12">
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Attendance Statistics</h6>
                </div>
                <div class="card-body">
                    <div class="chart-area">
                        <canvas id="attendanceChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>
            </main>
        </div>
    </div>
    <!-- End of Page Content -->

<!-- JavaScript for loading members when society is selected -->
<script>
document.getElementById('society_id').addEventListener('change', function() {
    const societyId = this.value;
    const memberListDiv = document.getElementById('member-list');
    
    if (!societyId) {
        memberListDiv.innerHTML = '<p>Select a society to load members.</p>';
        return;
    }
    
    // Show loading message
    memberListDiv.innerHTML = '<p>Loading members...</p>';
    
    // Fetch members for the selected society
    fetch(`../api/get_society_members.php?society_id=${societyId}`)
        .then(async response => {
            const text = await response.text();
            try {
                return JSON.parse(text);
            } catch (e) {
                throw new Error('Unexpected response: ' + text.substring(0, 120));
            }
        })
        .then(data => {
            if (data && data.error) {
                memberListDiv.innerHTML = `<p class="text-danger">${data.error}</p>`;
                return;
            }
            const members = Array.isArray(data) ? data : (data && Array.isArray(data.members) ? data.members : []);
            if (members.length === 0) {
                memberListDiv.innerHTML = '<p>No members found for this society.</p>';
                return;
            }

            // Create member attendance form
            let html = '<h5 class="mt-3">Member Attendance</h5>';
            html += '<div class="table-responsive">';
            html += '<table class="table table-bordered">';
            html += '<thead><tr><th>Name</th><th>Present</th><th>Absent</th><th>Excused</th></tr></thead>';
            html += '<tbody>';

            members.forEach(member => {
                html += `<tr>
                    <td>${member.first_name ?? ''} ${member.surname ?? ''}</td>
                    <td><input type="radio" name="member_attendance[${member.id}]" value="present" checked></td>
                    <td><input type="radio" name="member_attendance[${member.id}]" value="absent"></td>
                    <td><input type="radio" name="member_attendance[${member.id}]" value="excused"></td>
                </tr>`;
            });

            html += '</tbody></table></div>';
            memberListDiv.innerHTML = html;
        })
        .catch(error => {
            memberListDiv.innerHTML = `<p class="text-danger">Error loading members: ${error.message}</p>`;
        });
});

// Chart for attendance statistics
document.addEventListener('DOMContentLoaded', function() {
    const ctx = document.getElementById('attendanceChart');
    
    // Sample data - in a real application, this would be loaded from the server
    const attendanceData = {
        labels: ['January', 'February', 'March', 'April', 'May', 'June'],
        datasets: [
            {
                label: 'Present',
                backgroundColor: 'rgba(78, 115, 223, 0.2)',
                borderColor: 'rgba(78, 115, 223, 1)',
                data: [65, 70, 68, 72, 75, 80],
                fill: false
            },
            {
                label: 'Absent',
                backgroundColor: 'rgba(231, 74, 59, 0.2)',
                borderColor: 'rgba(231, 74, 59, 1)',
                data: [20, 15, 18, 14, 12, 10],
                fill: false
            },
            {
                label: 'Excused',
                backgroundColor: 'rgba(246, 194, 62, 0.2)',
                borderColor: 'rgba(246, 194, 62, 1)',
                data: [15, 15, 14, 14, 13, 10],
                fill: false
            }
        ]
    };
    
    new Chart(ctx, {
        type: 'line',
        data: attendanceData,
        options: {
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
});
</script>

</body>
</html>
