<?php 
include 'includes/config.php';
include 'includes/functions.php';
include 'includes/header.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Isi Absensi - DIGITAL PANDAI</title>
    <link href="assets/css/sweetalert2.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/style.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        .signature-container {
            width: 100%;
            margin-bottom: 1rem;
        }
        #signatureCanvas {
            width: 100%;
            height: 150px;
            background-color: #f8f9fa;
            border: 1px dashed #ccc;
            touch-action: none; /* Untuk mencegah scroll saat menandatangani di mobile */
        }
        .btn-clear-signature {
            margin-top: 0.5rem;
        }
        .card-header {
            font-weight: 600;
        }
        .form-label {
            font-weight: 500;
        }
        .btn-primary:disabled {
            background-color: #6c757d;
            border-color: #6c757d;
            cursor: not-allowed;
        }
    </style>
</head>
<body>
   <!-- <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="#">
                <i class="fas fa-user-check text-primary"></i>
                <span class="ms-2">Absensi Digital</span>
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="index.php">Beranda</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="attendance.php">Isi Absensi</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav> -->

    <div class="container mt-4">
        <?php
        $activeEvent = getActiveEvent();
        if (!$activeEvent) {
            echo '
<div class="alert alert-info text-center py-4">
    <i class="fas fa-info-circle fa-2x mb-3 text-primary"></i>
    <h5 class="fw-semibold">Tidak ada kegiatan aktif saat ini</h5>
    <p class="mb-0">Silakan hubungi administrator untuk informasi lebih lanjut</p>
</div>';
        } else {
        ?>
        <div class="row justify-content-center">
            <div class="col-lg-8">
                <div class="card shadow-sm">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0"><i class="fas fa-calendar-check me-2"></i> <?= htmlspecialchars($activeEvent['nama_event']) ?></h5>
                    </div>
                    <div class="card-body">
                        <form id="attendanceForm">
                            <input type="hidden" name="id_event" value="<?= $activeEvent['id_event'] ?>">
                            
                            <div class="mb-3">
                                <label for="nama_lengkap" class="form-label">Nama Lengkap</label>
                                <input type="text" class="form-control" id="nama_lengkap" name="nama_lengkap" required>
                            </div>
                            
                            <div class="mb-3">
                                <label for="jabatan" class="form-label">Jabatan</label>
                                <input type="text" class="form-control" id="jabatan" name="jabatan" required>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Tanda Tangan</label>
                                <div class="signature-container">
                                    <canvas id="signatureCanvas"></canvas>
                                    <button type="button" id="clearSignature" class="btn btn-sm btn-outline-secondary btn-clear-signature" title="Hapus Tanda Tangan">
                                        <i class="fas fa-eraser me-1"></i> Hapus
                                    </button>
                                </div>
                                <input type="hidden" id="tanda_tangan" name="tanda_tangan">
                            </div>
                            
                            <button type="submit" class="btn btn-primary w-100 py-2" id="submitBtn" disabled>
                                <i class="fas fa-paper-plane me-2"></i> Kirim Absensi
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <?php } ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="assets/js/sweetalert2.min.js"></script>
    <script>
        // Initialize Signature Canvas
        const canvas = document.getElementById('signatureCanvas');
        const ctx = canvas.getContext('2d');
        let isDrawing = false;
        let lastX = 0;
        let lastY = 0;
        let hasSigned = false; // Tambahkan variabel untuk melacak apakah sudah ada tanda tangan

        // Set canvas dimensions
        function resizeCanvas() {
            const container = canvas.parentElement;
            const rect = container.getBoundingClientRect();
            canvas.width = rect.width;
            canvas.height = 150;
            ctx.fillStyle = '#f8f9fa';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            ctx.strokeStyle = '#000';
            ctx.lineWidth = 2;
            ctx.lineCap = 'round';
            ctx.lineJoin = 'round';
        }

        // Function to check form validity
        function checkFormValidity() {
            const namaLengkap = document.getElementById('nama_lengkap').value.trim();
            const jabatan = document.getElementById('jabatan').value.trim();
            const submitBtn = document.getElementById('submitBtn');
            
            // Cek apakah sudah ada tanda tangan yang valid (hasSigned = true)
            submitBtn.disabled = !(namaLengkap && jabatan && hasSigned);
        }

        // Initialize canvas
        resizeCanvas();
        window.addEventListener('resize', resizeCanvas);
        checkFormValidity();

        // Drawing functions
        function startDrawing(e) {
            isDrawing = true;
            [lastX, lastY] = [e.offsetX || e.touches[0].clientX - canvas.getBoundingClientRect().left, 
                              e.offsetY || e.touches[0].clientY - canvas.getBoundingClientRect().top];
        }

        function draw(e) {
            if (!isDrawing) return;
            
            const x = e.offsetX || e.touches[0].clientX - canvas.getBoundingClientRect().left;
            const y = e.offsetY || e.touches[0].clientY - canvas.getBoundingClientRect().top;
            
            ctx.beginPath();
            ctx.moveTo(lastX, lastY);
            ctx.lineTo(x, y);
            ctx.stroke();
            [lastX, lastY] = [x, y];
            
            // Set flag bahwa sudah ada tanda tangan
            if (!hasSigned) {
                hasSigned = true;
                document.getElementById('tanda_tangan').value = canvas.toDataURL();
                checkFormValidity();
            }
        }

        function stopDrawing() {
            if (isDrawing) {
                isDrawing = false;
                // Hanya update data URL jika benar-benar ada tanda tangan
                if (hasSigned) {
                    document.getElementById('tanda_tangan').value = canvas.toDataURL();
                }
                checkFormValidity();
            }
        }

        function clearSignature() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            document.getElementById('tanda_tangan').value = '';
            hasSigned = false; // Reset flag tanda tangan
            checkFormValidity();
        }

        // Event listeners for mouse
        canvas.addEventListener('mousedown', startDrawing);
        canvas.addEventListener('mousemove', draw);
        canvas.addEventListener('mouseup', stopDrawing);
        canvas.addEventListener('mouseout', stopDrawing);

        // Event listeners for touch
        canvas.addEventListener('touchstart', (e) => {
            e.preventDefault();
            startDrawing(e);
        });

        canvas.addEventListener('touchmove', (e) => {
            e.preventDefault();
            draw(e);
        });

        canvas.addEventListener('touchend', (e) => {
            e.preventDefault();
            stopDrawing();
        });

        document.getElementById('clearSignature').addEventListener('click', clearSignature);

        // Event listeners for form fields
        document.getElementById('nama_lengkap').addEventListener('input', checkFormValidity);
        document.getElementById('jabatan').addEventListener('input', checkFormValidity);

        // Form Submission
        document.getElementById('attendanceForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            if (!document.getElementById('tanda_tangan').value) {
                Swal.fire({
                    icon: 'error',
                    title: 'Oops...',
                    text: 'Harap berikan tanda tangan Anda!',
                    confirmButtonColor: '#0d6efd'
                });
                return;
            }
            
            const formData = new FormData(this);
            
            fetch('process_attendance.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Berhasil!',
                        text: data.message,
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#0d6efd'
                    }).then(() => {
                        window.location.href = 'index.php';
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Gagal',
                        text: data.message,
                        confirmButtonColor: '#0d6efd'
                    });
                }
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Terjadi kesalahan saat mengirim data.',
                    confirmButtonColor: '#0d6efd'
                });
            });
        });
    </script>
</body>
</html>