<?php
/**
 * Auto Alert & Notification System
 * Generates alerts for overdue trips, anomalies, and system events
 */

/**
 * Check and generate all automatic alerts
 */
function generateAutoAlerts($pdo) {
    $alerts = [];

    // 1. Overdue pending unloading (>4 hours old)
    $stmt = $pdo->query("SELECT t.id, t.created_date, v.vehicle_number, t.loading_time, t.loading_location,
                                dr.full_name as driver_name, t.created_at
                         FROM tripper_records t
                         LEFT JOIN vehicles v ON t.vehicle_id = v.id
                         LEFT JOIN drivers dr ON t.driver_id = dr.id
                         WHERE t.status = 'pending_unloading'
                         ORDER BY t.created_at ASC");
    $pending = $stmt->fetchAll();
    foreach ($pending as $p) {
        $hours_ago = (time() - strtotime($p['created_at'])) / 3600;
        $urgency = 'warning';
        if ($hours_ago > 24) $urgency = 'danger';
        elseif ($hours_ago > 8) $urgency = 'warning';
        else $urgency = 'info';

        $alerts[] = [
            'type' => 'overdue_unloading',
            'urgency' => $urgency,
            'icon' => 'fas fa-exclamation-triangle',
            'title' => 'Pending Unloading: ' . ($p['vehicle_number'] ?? 'Unknown'),
            'message' => 'Vehicle ' . ($p['vehicle_number'] ?? '?') . ' loaded at ' . ($p['loading_location'] ?? '?') .
                        ' (' . round($hours_ago, 1) . ' hrs ago). Driver: ' . ($p['driver_name'] ?? '?'),
            'record_id' => $p['id'],
            'hours_ago' => $hours_ago,
            'link' => SITE_URL . '/tripper/add_unloading.php?id=' . $p['id']
        ];
    }

    // 2. Odometer anomalies - dozar end < start
    $stmt = $pdo->query("SELECT d.id, v.vehicle_number, d.start_odometer, d.end_odometer, d.created_date
                         FROM dozar_records d
                         LEFT JOIN vehicles v ON d.vehicle_id = v.id
                         WHERE d.end_odometer IS NOT NULL AND d.end_odometer < d.start_odometer
                         ORDER BY d.created_date DESC LIMIT 10");
    foreach ($stmt->fetchAll() as $a) {
        $alerts[] = [
            'type' => 'odometer_anomaly',
            'urgency' => 'warning',
            'icon' => 'fas fa-tachometer-alt',
            'title' => 'Odometer Anomaly: ' . $a['vehicle_number'],
            'message' => 'End odometer (' . $a['end_odometer'] . ') < Start (' . $a['start_odometer'] . ') on ' . $a['created_date'],
            'record_id' => $a['id'],
            'link' => SITE_URL . '/dozar/edit.php?id=' . $a['id']
        ];
    }

    // 3. Tripper odometer anomalies
    $stmt = $pdo->query("SELECT t.id, v.vehicle_number, t.loading_start_odometer, t.unloading_end_odometer, t.created_date
                         FROM tripper_records t
                         LEFT JOIN vehicles v ON t.vehicle_id = v.id
                         WHERE t.unloading_end_odometer IS NOT NULL AND t.unloading_end_odometer < t.loading_start_odometer
                         ORDER BY t.created_date DESC LIMIT 10");
    foreach ($stmt->fetchAll() as $a) {
        $alerts[] = [
            'type' => 'odometer_anomaly',
            'urgency' => 'warning',
            'icon' => 'fas fa-tachometer-alt',
            'title' => 'KM Anomaly: ' . $a['vehicle_number'],
            'message' => 'End KM (' . $a['unloading_end_odometer'] . ') < Start KM (' . $a['loading_start_odometer'] . ') on ' . $a['created_date'],
            'record_id' => $a['id'],
            'link' => SITE_URL . '/tripper/view.php?id=' . $a['id']
        ];
    }

    // 4. Vehicles with no activity in 7+ days
    $stmt = $pdo->query("SELECT v.id, v.vehicle_number, v.vehicle_type,
                                GREATEST(
                                    COALESCE((SELECT MAX(d.created_date) FROM dozar_records d WHERE d.vehicle_id = v.id), '2000-01-01'),
                                    COALESCE((SELECT MAX(t.created_date) FROM tripper_records t WHERE t.vehicle_id = v.id), '2000-01-01')
                                ) as last_used
                         FROM vehicles v WHERE v.is_active = 1
                         HAVING last_used < DATE_SUB(CURDATE(), INTERVAL 7 DAY)
                         ORDER BY last_used ASC LIMIT 10");
    foreach ($stmt->fetchAll() as $v) {
        $days = (int)((time() - strtotime($v['last_used'])) / 86400);
        if ($v['last_used'] === '2000-01-01') {
            $msg = 'Never used';
        } else {
            $msg = 'Last used ' . $days . ' days ago (' . $v['last_used'] . ')';
        }
        $alerts[] = [
            'type' => 'idle_vehicle',
            'urgency' => 'info',
            'icon' => 'fas fa-car-battery',
            'title' => 'Idle Vehicle: ' . $v['vehicle_number'],
            'message' => $v['vehicle_type'] . ' - ' . $msg,
            'record_id' => $v['id'],
            'link' => SITE_URL . '/vehicles/index.php'
        ];
    }

    // 5. Duplicate entries today (same vehicle, same day, multiple dozar)
    $stmt = $pdo->query("SELECT v.vehicle_number, d.created_date, COUNT(*) as entry_count
                         FROM dozar_records d
                         LEFT JOIN vehicles v ON d.vehicle_id = v.id
                         WHERE d.created_date >= DATE_SUB(CURDATE(), INTERVAL 3 DAY)
                         GROUP BY d.vehicle_id, d.created_date
                         HAVING entry_count > 2
                         ORDER BY d.created_date DESC");
    foreach ($stmt->fetchAll() as $dup) {
        $alerts[] = [
            'type' => 'duplicate_entries',
            'urgency' => 'warning',
            'icon' => 'fas fa-clone',
            'title' => 'Multiple Entries: ' . $dup['vehicle_number'],
            'message' => $dup['entry_count'] . ' dozar entries on ' . $dup['created_date'],
            'record_id' => null,
            'link' => SITE_URL . '/dozar/index.php'
        ];
    }

    return $alerts;
}

/**
 * Get alert count by urgency
 */
function getAlertCounts($alerts) {
    $counts = ['danger' => 0, 'warning' => 0, 'info' => 0, 'total' => count($alerts)];
    foreach ($alerts as $a) {
        if (isset($counts[$a['urgency']])) $counts[$a['urgency']]++;
    }
    return $counts;
}

/**
 * Get notification bell HTML for header
 */
function getNotificationBell($pdo) {
    $pending_count = $pdo->query("SELECT COUNT(*) FROM tripper_records WHERE status = 'pending_unloading'")->fetchColumn();

    $html = '<div class="dropdown d-inline-block me-2">';
    $html .= '<button class="btn btn-sm btn-outline-secondary position-relative" data-bs-toggle="dropdown" data-bs-auto-close="outside" id="notifBell">';
    $html .= '<i class="fas fa-bell"></i>';
    if ($pending_count > 0) {
        $html .= ' <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">' . $pending_count . '</span>';
    }
    $html .= '</button>';
    $html .= '<div class="dropdown-menu dropdown-menu-end shadow" style="width:350px; max-height:400px; overflow-y:auto;">';
    $html .= '<h6 class="dropdown-header"><i class="fas fa-bell"></i> Notifications</h6>';

    if ($pending_count > 0) {
        $stmt = $pdo->query("SELECT t.id, v.vehicle_number, t.loading_location, t.created_at
                             FROM tripper_records t
                             LEFT JOIN vehicles v ON t.vehicle_id = v.id
                             WHERE t.status = 'pending_unloading'
                             ORDER BY t.created_at ASC LIMIT 10");
        foreach ($stmt->fetchAll() as $p) {
            $hrs = round((time() - strtotime($p['created_at'])) / 3600, 1);
            $color = $hrs > 24 ? 'danger' : ($hrs > 8 ? 'warning' : 'info');
            $html .= '<a class="dropdown-item small border-start border-3 border-' . $color . '" href="' . SITE_URL . '/tripper/add_unloading.php?id=' . $p['id'] . '">';
            $html .= '<strong>' . htmlspecialchars($p['vehicle_number'] ?? '?') . '</strong> - Pending<br>';
            $html .= '<small class="text-muted">' . htmlspecialchars($p['loading_location'] ?? '') . ' &middot; ' . $hrs . 'h ago</small>';
            $html .= '</a>';
        }
    } else {
        $html .= '<div class="dropdown-item text-center text-muted small py-3"><i class="fas fa-check-circle text-success"></i> All clear!</div>';
    }

    $html .= '<div class="dropdown-divider"></div>';
    $html .= '<a class="dropdown-item text-center small text-primary" href="' . SITE_URL . '/dashboard.php#alerts"><i class="fas fa-list"></i> View All Alerts</a>';
    $html .= '</div></div>';

    return $html;
}
