#!/usr/bin/php
<?php
/**
 * Opel Lifts - Auto Logout Cron Script
 * Run at 23:59 IST daily via crontab
 * 
 * Crontab entry:
 * 59 23 * * * /usr/bin/php /var/www/opel-attendance/cron/auto_logout.php >> /var/log/opel_auto_logout.log 2>&1
 */

require_once __DIR__ . '/../config/database.php';

date_default_timezone_set('Asia/Kolkata');

$db = Database::getConnection();
$today = date('Y-m-d');

echo "[" . date('Y-m-d H:i:s') . "] Running auto-logout for date: $today\n";

// Find employees who logged in but haven't logged out
$stmt = $db->prepare('
    SELECT DISTINCT a.employee_id, a.name, a.latitude, a.longitude, a.location_url 
    FROM attendance a 
    WHERE a.date = ? AND a.action = "Login" 
    AND a.employee_id NOT IN (
        SELECT employee_id FROM attendance WHERE date = ? AND action = "Logout"
    )
');
$stmt->execute([$today, $today]);
$pending = $stmt->fetchAll();

$count = 0;
foreach ($pending as $rec) {
    // Insert auto logout record
    $db->prepare('
        INSERT INTO attendance (employee_id, name, date, action, time, timestamp, latitude, longitude, location_url, ip_address, is_auto_logout) 
        VALUES (?, ?, ?, "Logout", "11:59:00 PM", NOW(), ?, ?, ?, "auto-system", 1)
    ')->execute([
        $rec['employee_id'], $rec['name'], $today,
        $rec['latitude'], $rec['longitude'], $rec['location_url']
    ]);
    
    // Push to Google Sheets
    $url = Config::get('GOOGLE_SHEETS_URL');
    if ($url) {
        $data = json_encode([
            'date' => $today,
            'employee_id' => $rec['employee_id'],
            'name' => $rec['name'],
            'action' => 'Logout',
            'time' => '11:59:00 PM',
            'location_url' => $rec['location_url'] ?? '',
            'latitude' => (string)($rec['latitude'] ?? 0),
            'longitude' => (string)($rec['longitude'] ?? 0),
            'ip_address' => 'auto-system',
            'auto_logout' => 'Yes'
        ]);
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $data,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_TIMEOUT => 15,
        ]);
        curl_exec($ch);
        curl_close($ch);
    }
    
    $count++;
    echo "  Auto-logout: {$rec['employee_id']} ({$rec['name']})\n";
}

echo "[" . date('Y-m-d H:i:s') . "] Auto-logout completed: $count employees\n";
