<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Staff Attendance Clock - RestPO</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { font-family: 'Outfit', sans-serif; }
        body { background: #0b0f17; color: white; }
        .glass-panel {
            background: rgba(255, 255, 255, 0.03);
            backdrop-filter: blur(16px);
            border: 1px solid rgba(255, 255, 255, 0.08);
        }
        .glowing-dot {
            box-shadow: 0 0 15px currentColor;
        }
        .keypad-btn {
            background: rgba(255, 255, 255, 0.04);
            border: 1px solid rgba(255, 255, 255, 0.07);
            transition: all 0.15s ease-in-out;
        }
        .keypad-btn:active {
            background: rgba(99, 102, 241, 0.2);
            border-color: rgba(99, 102, 241, 0.5);
            transform: scale(0.95);
        }
    </style>
</head>
<body class="min-h-screen flex flex-col justify-between p-4 sm:p-6" x-data="clockSystem()">
    
    <!-- Top Header -->
    <header class="w-full max-w-md mx-auto text-center mt-2">
        <div class="inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-xs font-semibold glass-panel text-slate-400">
            <i class="fas fa-store text-indigo-400"></i>
            <span><?php echo htmlspecialchars($cashier['rest_name']); ?></span>
        </div>
        <h1 class="text-xl font-bold mt-3 text-white">Branch Clock-In Portal</h1>
        <p class="text-xs text-slate-400 mt-0.5">Cashier: <?php echo htmlspecialchars($cashier['name']); ?></p>
    </header>

    <!-- Main Card -->
    <main class="w-full max-w-md mx-auto my-auto flex-grow flex flex-col justify-center py-6">
        <div class="glass-panel rounded-3xl p-6 shadow-2xl relative overflow-hidden">
            
            <!-- Glow Background Effect -->
            <div class="absolute -top-24 -left-24 w-48 h-48 rounded-full bg-indigo-500/10 blur-3xl pointer-events-none"></div>
            <div class="absolute -bottom-24 -right-24 w-48 h-48 rounded-full bg-emerald-500/5 blur-3xl pointer-events-none"></div>

            <!-- Geolocation Status -->
            <div class="flex items-center justify-between p-4 rounded-2xl glass-panel mb-5">
                <div class="flex items-center gap-3">
                    <div class="w-2.5 h-2.5 rounded-full glowing-dot"
                         :class="{
                             'bg-amber-400 text-amber-400 animate-pulse': geoState === 'detecting',
                             'bg-emerald-500 text-emerald-500': geoState === 'verified',
                             'bg-red-500 text-red-500': geoState === 'blocked'
                         }"></div>
                    <div>
                        <div class="text-xs font-bold text-white uppercase tracking-wider">Location Verification</div>
                        <div class="text-[10px] text-slate-400 mt-0.5" x-text="geoStatusText">Initializing GPS...</div>
                    </div>
                </div>
                <button @click="getGeoLocation(true)" class="p-2 rounded-lg bg-white/5 border border-white/10 text-slate-400 hover:text-white transition active:scale-90">
                    <i class="fas fa-sync text-xs"></i>
                </button>
            </div>

            <!-- PIN Display -->
            <div class="text-center mb-6">
                <label class="block text-xs font-semibold text-slate-400 uppercase tracking-widest mb-3">Enter Your Unique PIN</label>
                <div class="flex justify-center gap-2.5 mb-2 h-10 items-center">
                    <template x-for="i in 6">
                        <div class="w-3.5 h-3.5 rounded-full border-2 transition-all duration-150"
                             :class="pin.length >= i ? 'bg-indigo-400 border-indigo-400 scale-110 glowing-dot text-indigo-400' : 'border-slate-700 bg-transparent'"></div>
                    </template>
                </div>
                <div class="text-xs text-rose-400 font-medium h-4" x-text="errorMessage"></div>
            </div>

            <!-- Sleek Tap Keypad -->
            <div class="grid grid-cols-3 gap-3 mb-6">
                <template x-for="num in ['1','2','3','4','5','6','7','8','9']">
                    <button @click="pressKey(num)" class="keypad-btn py-4 rounded-2xl font-bold text-lg text-white hover:bg-white/10">
                        <span x-text="num"></span>
                    </button>
                </template>
                <button @click="clearPIN()" class="keypad-btn py-4 rounded-2xl font-bold text-xs text-rose-400 hover:bg-rose-500/10 hover:text-white uppercase tracking-wider">
                    Clear
                </button>
                <button @click="pressKey('0')" class="keypad-btn py-4 rounded-2xl font-bold text-lg text-white hover:bg-white/10">
                    0
                </button>
                <button @click="deleteLast()" class="keypad-btn py-4 rounded-2xl font-bold text-slate-400 hover:bg-white/10 hover:text-white flex items-center justify-center">
                    <i class="fas fa-backspace"></i>
                </button>
            </div>

            <!-- Submit Button -->
            <button @click="submitClockAction()" 
                    :disabled="pin.length < 4 || geoState !== 'verified' || loading"
                    class="w-full py-4 rounded-2xl font-bold text-sm text-white transition-all shadow-lg flex items-center justify-center gap-2 disabled:opacity-40 disabled:cursor-not-allowed"
                    :class="geoState === 'verified' ? 'bg-gradient-to-r from-indigo-500 to-indigo-600 hover:brightness-110 shadow-indigo-500/20' : 'bg-slate-800 text-slate-500 border border-white/5'">
                <template x-if="loading">
                    <i class="fas fa-spinner animate-spin"></i>
                </template>
                <template x-if="!loading">
                    <i class="fas fa-fingerprint text-base"></i>
                </template>
                <span x-text="loading ? 'Processing...' : 'Confirm Clock-In / Out'"></span>
            </button>
        </div>
    </main>

    <!-- Overlay Alert Modal -->
    <div x-show="modalOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm" style="display:none">
        <div class="w-full max-w-sm rounded-3xl p-6 text-center border shadow-2xl relative"
             :class="modalSuccess ? 'border-emerald-500/30 bg-[#0c1c16]' : 'border-rose-500/30 bg-[#1c0c0d]'"
             @click.away="modalOpen = false">
            
            <div class="w-14 h-14 rounded-full flex items-center justify-center mx-auto mb-4"
                 :class="modalSuccess ? 'bg-emerald-500/15 text-emerald-400' : 'bg-rose-500/15 text-rose-400'">
                <i class="fas" :class="modalSuccess ? (modalAction === 'in' ? 'fa-door-open text-xl' : 'fa-door-closed text-xl') : 'fa-exclamation-triangle text-xl'"></i>
            </div>
            
            <h3 class="text-lg font-bold text-white" x-text="modalTitle"></h3>
            <p class="text-xs text-slate-400 mt-2 leading-relaxed" x-text="modalMessage"></p>
            
            <button @click="modalOpen = false" class="w-full mt-5 py-3 rounded-xl font-semibold text-xs text-white uppercase tracking-wider"
                    :class="modalSuccess ? 'bg-emerald-500 hover:bg-emerald-600' : 'bg-rose-500 hover:bg-rose-600'">
                Close
            </button>
        </div>
    </div>

    <!-- Bottom Footer -->
    <footer class="w-full text-center text-[10px] text-slate-600 mb-2">
        Powered by RestPO Attendance Geofence System &bull; &copy; <?php echo date('Y'); ?>
    </footer>

    <script>
        function clockSystem() {
            return {
                cashierId: <?php echo $cashier['id']; ?>,
                cashierLat: <?php echo $cashier['latitude'] ?? 'null'; ?>,
                cashierLng: <?php echo $cashier['longitude'] ?? 'null'; ?>,
                cashierRadius: <?php echo $cashier['radius'] ?? 100; ?>,

                pin: '',
                geoState: 'detecting', // detecting | verified | blocked
                geoStatusText: 'Initializing GPS...',
                lat: 0,
                lng: 0,
                loading: false,
                errorMessage: '',

                // Modal
                modalOpen: false,
                modalSuccess: false,
                modalTitle: '',
                modalMessage: '',
                modalAction: '', // in | out

                init() {
                    if (this.cashierLat === null || this.cashierLng === null) {
                        this.geoState = 'blocked';
                        this.geoStatusText = 'Branch geofence not configured by HR.';
                        return;
                    }
                    this.getGeoLocation();
                },

                getGeoLocation(force = false) {
                    if (force) {
                        this.geoState = 'detecting';
                        this.geoStatusText = 'Refreshing location...';
                    }
                    
                    if (!navigator.geolocation) {
                        this.geoState = 'blocked';
                        this.geoStatusText = 'Geolocation not supported by your browser.';
                        return;
                    }

                    navigator.geolocation.getCurrentPosition(
                        (pos) => {
                            this.lat = pos.coords.latitude;
                            this.lng = pos.coords.longitude;
                            
                            // Check distance using Haversine formula
                            const dist = this.calculateDistance(this.lat, this.lng, this.cashierLat, this.cashierLng);
                            if (dist <= this.cashierRadius) {
                                this.geoState = 'verified';
                                this.geoStatusText = `Verified inside branch range (${Math.round(dist)}m).`;
                            } else {
                                this.geoState = 'blocked';
                                this.geoStatusText = `Blocked: Outside branch range (${Math.round(dist)}m away).`;
                            }
                        },
                        (err) => {
                            this.geoState = 'blocked';
                            this.geoStatusText = 'GPS Disabled: Please enable location permissions.';
                            console.error(err);
                        },
                        { enableHighAccuracy: true, timeout: 10000, maximumAge: 0 }
                    );
                },

                calculateDistance(lat1, lon1, lat2, lon2) {
                    const R = 6371e3; // Earth radius in meters
                    const dLat = (lat2 - lat1) * Math.PI / 180;
                    const dLon = (lon2 - lon1) * Math.PI / 180;
                    const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                              Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
                              Math.sin(dLon/2) * Math.sin(dLon/2);
                    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
                    return R * c; // in meters
                },

                pressKey(num) {
                    if (this.pin.length < 6) {
                        this.pin += num;
                        this.errorMessage = '';
                    }
                },

                deleteLast() {
                    this.pin = this.pin.slice(0, -1);
                    this.errorMessage = '';
                },

                clearPIN() {
                    this.pin = '';
                    this.errorMessage = '';
                },

                submitClockAction() {
                    if (this.pin.length < 4 || this.geoState !== 'verified' || this.loading) return;
                    
                    this.loading = true;
                    this.errorMessage = '';

                    const fd = new FormData();
                    fd.append('cashier_id', this.cashierId);
                    fd.append('pin', this.pin);
                    fd.append('latitude', this.lat);
                    fd.append('longitude', this.lng);

                    fetch('/clock/submit', {
                        method: 'POST',
                        body: fd
                    })
                    .then(r => r.json())
                    .then(res => {
                        this.loading = false;
                        if (res.success) {
                            this.modalSuccess = true;
                            this.modalTitle = res.action === 'in' ? 'Clock In Successful' : 'Clock Out Successful';
                            this.modalMessage = res.message;
                            this.modalAction = res.action;
                            this.modalOpen = true;
                            this.clearPIN();
                        } else {
                            this.errorMessage = res.message;
                        }
                    })
                    .catch(err => {
                        this.loading = false;
                        this.errorMessage = 'Network error. Please try again.';
                        console.error(err);
                    });
                }
            };
        }
    </script>
</body>
</html>
