<?php
error_log("DEBUG: functions.php is being loaded");
require_once __DIR__ . '/db.php';

function logAudit($action, $details = '') {
    $userName = $_SESSION['user_name'] ?? 'System';
    $userRole = $_SESSION['user_role'] ?? 'system';
    $companyId = $_SESSION['company_id'] ?? null;
    
    if (!$companyId && isset($_SESSION['user_id'])) {
        // Fallback: fetch company_id if not in session
        $u = fetch("SELECT company_id FROM users WHERE id = ?", [$_SESSION['user_id']]);
        if ($u) {
            $companyId = $u['company_id'];
            $_SESSION['company_id'] = $companyId;
        }
    }

    $sql = "INSERT INTO audit_logs (company_id, user_name, user_role, action, details, created_at) VALUES (?, ?, ?, ?, ?, NOW())";
    query($sql, [$companyId, $userName, $userRole, $action, $details]);
}

/**
 * Sanitizes output for HTML
 */
function e($text) {
    return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}

/**
 * Format currency using company settings
 */
function formatCurrency($amount) {
    $currency = $_SESSION['company_currency'] ?? '$';
    return $currency . ' ' . number_format((float)$amount, 2);
}

/**
 * Generates a clean URL
 */
function url($page = '', $params = []) {
    $base_dir = defined('APP_BASE_PATH') ? APP_BASE_PATH : '/';
    $url = $base_dir . ltrim($page, '/');
    
    if (!empty($params)) {
        $url .= '?' . http_build_query($params);
    }
    
    return $url;
}

/**
 * Creates a system notification for the company's owners and managers.
 */
function createNotification($companyId, $type, $title, $message, $targetUrl = null, $referenceKey = null) {
    if (!$companyId) return false;
    
    // Prevent duplicate unread notifications if a reference key is provided
    if ($referenceKey) {
        $existing = fetch("
            SELECT id FROM system_notifications 
            WHERE company_id = ? AND reference_key = ? AND is_read = 0
        ", [$companyId, $referenceKey]);
        
        if ($existing) {
            return false; // Already notified and still unread
        }
    }
    
    $sql = "INSERT INTO system_notifications (company_id, type, title, message, target_url, reference_key) VALUES (?, ?, ?, ?, ?, ?)";
    query($sql, [$companyId, $type, $title, $message, $targetUrl, $referenceKey]);
    return true;
}

/**
 * Automatically checks employee daily total hours worked.
 * If > company standard working hours, creates/updates a pending overtime request.
 * If <= company standard working hours, removes any pending overtime request.
 */
function processDailyOvertime($employee_id, $company_id, $date) {
    // 1. Fetch employee's shift details (specifically working_hours from shifts table via employee's shift_id)
    $employee_shift = fetch("
        SELECT s.working_hours, e.reporting_manager_id 
        FROM employees e 
        LEFT JOIN shifts s ON e.shift_id = s.id 
        WHERE e.id = ? AND e.company_id = ?
    ", [$employee_id, $company_id]);
    
    $standard_hours = ($employee_shift && $employee_shift['working_hours'] !== null) ? (float)$employee_shift['working_hours'] : 8.00;
    $manager_id = $employee_shift ? $employee_shift['reporting_manager_id'] : null;

    // 3. Calculate total hours worked on this day
    $sessions = fetchAll("SELECT clock_in, clock_out FROM attendance WHERE employee_id = ? AND company_id = ? AND date = ?", [$employee_id, $company_id, $date]);
    
    $totalSeconds = 0;
    foreach ($sessions as $s) {
        if ($s['clock_out']) {
            $totalSeconds += strtotime($s['clock_out']) - strtotime($s['clock_in']);
        }
    }
    $total_hours = round($totalSeconds / 3600, 2);

    if ($total_hours > $standard_hours) {
        $overtime_hours = $total_hours - $standard_hours;
        
        // Check if overtime request already exists for this date/employee/company
        $existing = fetch("SELECT id, status FROM overtime_requests WHERE employee_id = ? AND company_id = ? AND date = ?", [$employee_id, $company_id, $date]);
        if ($existing) {
            // Update existing request hours ONLY if it is still pending
            if ($existing['status'] === 'pending') {
                query("UPDATE overtime_requests SET hours = ?, reporting_manager_id = ? WHERE id = ?", [$overtime_hours, $manager_id, $existing['id']]);
            }
        } else {
            // Create new overtime request
            query("INSERT INTO overtime_requests (company_id, employee_id, reporting_manager_id, date, hours, status) VALUES (?, ?, ?, ?, ?, 'pending')", 
                  [$company_id, $employee_id, $manager_id, $date, $overtime_hours]);
        }
    } else {
        // If hours dropped below standard (e.g. log edited/deleted), and there's a pending overtime request, delete it
        query("DELETE FROM overtime_requests WHERE employee_id = ? AND company_id = ? AND date = ? AND status = 'pending'", [$employee_id, $company_id, $date]);
    }
}
