<?php
// pages/service_attendance_detail.php
requireRole('any');

$date = isset($_GET['date']) ? $_GET['date'] : null;

if (!$date) {
    echo "<div class='alert alert-danger'>No date specified.</div>";
    return;
}

// Fetch Service Info
$stmt = $pdo->prepare("SELECT * FROM services WHERE service_date = ?");
$stmt->execute([$date]);
$service = $stmt->fetch();
$service_name = $service ? ($service['type'] . ($service['name'] ? " - " . $service['name'] : "")) : getServiceName($date, $pdo);

// Fetch All entries for this service from attendance table directly
$stmt = $pdo->prepare("
    SELECT a.id, a.in_time as arrival_time, a.was_late, m.full_name, m.phone, m.unit,
           IF(a.was_late = 1, 'late', 'present') as status
    FROM attendance a
    JOIN members m ON a.member_id = m.id
    WHERE DATE(a.in_time) = ?
    ORDER BY a.in_time ASC
");
$stmt->execute([$date]);
$attendees = $stmt->fetchAll();

// Total counts
$present_count = 0;
$late_count = 0;
foreach ($attendees as $a) {
    if ($a['status'] === 'late') $late_count++;
    else $present_count++;
}
?>

<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
    <div>
        <a href="index.php?page=reports&tab=spool" class="btn" style="background: transparent; border: 1px solid #444; margin-bottom: 10px; display: inline-block;">
            <i class="fas fa-arrow-left"></i> Back to Spool
        </a>
        <h1>Attendance Details: <?php echo date("F j, Y", strtotime($date)); ?></h1>
        <p style="color: #888;"><?php echo htmlspecialchars($service_name); ?></p>
    </div>
    <div style="text-align: right;">
        <button onclick="window.print()" class="btn no-print"><i class="fas fa-print"></i> Print List</button>
    </div>
</div>

<div class="dashboard-grid no-print">
    <div class="card">
        <div class="stat-label">Present</div>
        <div class="stat-value" style="color: var(--success-color);"><?php echo $present_count; ?></div>
    </div>
    <div class="card">
        <div class="stat-label">Late</div>
        <div class="stat-value" style="color: #dfdf00;"><?php echo $late_count; ?></div>
    </div>
    <div class="card">
        <div class="stat-label">Total</div>
        <div class="stat-value"><?php echo count($attendees); ?></div>
    </div>
</div>

<div class="card">
    <div class="table-responsive">
        <table>
            <thead>
                <tr>
                    <th>#</th>
                    <th>Full Name</th>
                    <th>Unit / Dept</th>
                    <th>Status</th>
                    <th>Arrival Time</th>
                    <th class="no-print">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($attendees)): ?>
                <tr><td colspan="6" style="text-align: center; color: #888;">No attendance records found for this service.</td></tr>
                <?php else: ?>
                <?php $idx = 1; foreach ($attendees as $a): ?>
                <tr>
                    <td><?php echo $idx++; ?></td>
                    <td><strong><?php echo htmlspecialchars($a['full_name']); ?></strong></td>
                    <td><small><?php echo htmlspecialchars($a['unit'] ?? '---'); ?></small></td>
                    <td>
                        <?php if ($a['status'] === 'late'): ?>
                            <span class="badge" style="background: #dfdf00; color: #000;">LATE</span>
                        <?php else: ?>
                            <span class="badge" style="background: var(--success-color); color: #000;">PRESENT</span>
                        <?php endif; ?>
                    </td>
                    <td><?php echo $a['arrival_time'] ? date("g:i A", strtotime($a['arrival_time'])) : '---'; ?></td>
                    <td class="no-print">
                        <?php 
                            $timeOnly = $a['arrival_time'] ? date("H:i", strtotime($a['arrival_time'])) : ''; 
                            $datePart = $a['arrival_time'] ? date("Y-m-d", strtotime($a['arrival_time'])) : $date;
                        ?>
                        <button class="btn" style="padding: 2px 8px; font-size: 0.8rem; background: #555;"
                                onclick="openEditModal(<?php echo $a['id']; ?>, '<?php echo addslashes($a['full_name']); ?>', '<?php echo $timeOnly; ?>', <?php echo $a['was_late']; ?>, '<?php echo $datePart; ?>')">
                            Edit
                        </button>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<style>
    @media print {
        header, nav, .no-print, .btn { display: none !important; }
        .container { width: 100% !important; max-width: none !important; margin: 0 !important; padding: 0 !important; }
        html, body { background-color: #ffffff !important; color: #000000 !important; height: auto !important; }
        .card { border: none !important; background-color: #ffffff !important; box-shadow: none !important; margin-bottom: 10px !important; }
        
        table, tr, td, th { background-color: #ffffff !important; color: #000000 !important; }
        table th, table td { border: 1px solid #ccc !important; padding: 4px 8px !important; }
        .badge { 
             border: 1px solid #000 !important; 
             color: #000 !important; 
        }
        /* Hide Action Column in Print */
        th:last-child, td:last-child { display: none !important; }
    }
</style>

<!-- Edit Modal -->
<div id="editModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 1000; justify-content: center; align-items: center;">
    <div class="card" style="width: 100%; max-width: 400px; position: relative;">
        <h3 style="margin-top: 0;">Edit Attendance</h3>
        <button onclick="closeEditModal()" style="position: absolute; top: 15px; right: 15px; background: none; border: none; color: #aaa; font-size: 1.2rem; cursor: pointer;">&times;</button>
        
        <form id="editForm" onsubmit="submitEdit(event)">
            <input type="hidden" name="id" id="edit_id">
            <input type="hidden" name="type" value="update">
            
            <div class="form-group">
                <label>Member Name</label>
                <input type="text" id="edit_name" class="form-control" readonly style="background: #333; color: #bbb;">
            </div>
            
            <div class="form-group">
                <label>Arrival Time</label>
                <input type="time" name="in_time_time" id="edit_time" class="form-control" required>
                <!-- Hidden date part to reconstruct full datetime if needed, or backend handles it -->
                <input type="hidden" id="edit_date_part"> 
            </div>
            
            <div class="form-group">
                <label>Status override</label>
                <select name="was_late" id="edit_status" class="form-control">
                    <option value="0">Present (On Time)</option>
                    <option value="1">Late</option>
                </select>
            </div>
            
            <button type="submit" class="btn btn-block" style="background-color: var(--primary-color);">Save Changes</button>
        </form>
    </div>
</div>

<script>
    function openEditModal(id, name, timeStr, wasLate, datePart) {
        document.getElementById('edit_id').value = id;
        document.getElementById('edit_name').value = name;
        
        // timeStr is like "09:30:00" or just "09:30"
        // Input type=time needs HH:mm
        let formattedTime = timeStr;
        if(timeStr.length > 5) formattedTime = timeStr.substring(0, 5);
        
        document.getElementById('edit_time').value = formattedTime;
        document.getElementById('edit_status').value = wasLate;
        document.getElementById('edit_date_part').value = datePart;
        
        document.getElementById('editModal').style.display = 'flex';
    }
    
    function closeEditModal() {
        document.getElementById('editModal').style.display = 'none';
    }
    
    // Close on click outside
    window.onclick = function(event) {
        if (event.target == document.getElementById('editModal')) {
            closeEditModal();
        }
    }

    async function submitEdit(e) {
        e.preventDefault();
        const form = document.getElementById('editForm');
        const formData = new FormData(form);
        
        // We need to combine date and time for full timestamp if backend expects it
        // Or simpler: pass the time and let backend merge with existing date?
        // Let's pass 'custom_time' as full datetime string Y-m-d H:i:s
        const datePart = document.getElementById('edit_date_part').value;
        const timePart = document.getElementById('edit_time').value;
        const fullDateTime = `${datePart} ${timePart}:00`;
        
        formData.set('custom_time', fullDateTime);
        
        try {
            const res = await fetch('api/attendance_action.php', {
                method: 'POST',
                body: formData
            });
            const data = await res.json();
            
            if (data.success) {
                alert('Updated successfully');
                location.reload();
            } else {
                alert('Error: ' + data.message);
            }
        } catch (err) {
            alert('Request failed');
            console.error(err);
        }
    }
</script>
