<?php
/**
 * api/assistant_status.php (Localhost version)
 * Fetch pending tasks, overdue projects, and notifications for the Smart Assistant.
 */

require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/portal_auth.php';

header('Content-Type: application/json');

$user = function_exists('auth_user') ? auth_user() : null;
if (!$user) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Unauthorized']);
    exit;
}

$pdo = crm_pdo();

$response = [
    'ok' => true,
    'notifications' => []
];

$userId = (int)($user['id'] ?? 0);
$role = strtolower(trim((string)($user['role'] ?? '')));
$isAdmin = in_array($role, ['admin', 'administrator', 'manager', 'owner', 'super_admin', 'secretary', 'secretariat', 'office'], true);

// Try to fetch active/pending project assignments
try {
    if ($isAdmin) {
        // Admin sees overdue projects (not completed/cancelled)
        $stmt = $pdo->query("SELECT COUNT(*) FROM projects WHERE status != 'completed' AND status != 'cancelled' AND created_at < DATE_SUB(NOW(), INTERVAL 1 DAY)");
        $overdueCount = (int)$stmt->fetchColumn();
        if ($overdueCount > 0) {
            $response['notifications'][] = [
                'type'    => 'projects',
                'title'   => $overdueCount . ' Ενεργά Έργα',
                'message' => 'Υπάρχουν έργα που εκκρεμούν.',
                'url'     => '/gopools/public/projects/index.php',
                'icon'    => '📋'
            ];
        }
    } else {
        // Check if this is a partner portal user
        $partnerId = 0;
        if (function_exists('auth_partner_id')) {
            $partnerId = auth_partner_id();
        }

        if ($partnerId > 0) {
            // Partner: show active assignments
            $stmt = $pdo->prepare("
                SELECT COUNT(DISTINCT pa.id)
                FROM project_assignments pa
                JOIN projects p ON p.id = pa.project_id
                WHERE p.status != 'completed' AND p.status != 'cancelled'
                AND pa.status != 'completed'
                AND pa.external_partner_id = :pid
            ");
            $stmt->execute([':pid' => $partnerId]);
            $partnerCount = (int)$stmt->fetchColumn();

            if ($partnerCount > 0) {
                $response['notifications'][] = [
                    'type'    => 'projects',
                    'title'   => $partnerCount . ' Ενεργά Έργα',
                    'message' => 'Έχετε ανατεθειμένα έργα που αναμένουν εργασία.',
                    'url'     => '/gopools/public/partners/my_jobs.php',
                    'icon'    => '📋'
                ];
            }
        } else {
            // Employee: show active assignments
            $stmt = $pdo->prepare("
                SELECT COUNT(DISTINCT pa.id)
                FROM project_assignments pa
                JOIN projects p ON p.id = pa.project_id
                WHERE p.status != 'completed' AND p.status != 'cancelled'
                AND pa.status != 'completed'
                AND pa.employee_id = (SELECT employee_id FROM users WHERE id = :uid LIMIT 1)
            ");
            $stmt->execute([':uid' => $userId]);
            $empCount = (int)$stmt->fetchColumn();

            if ($empCount > 0) {
                $response['notifications'][] = [
                    'type'    => 'projects',
                    'title'   => $empCount . ' Ενεργά Έργα',
                    'message' => 'Έχετε ανατεθειμένα έργα που αναμένουν εργασία.',
                    'url'     => '/gopools/public/employees/my_jobs.php',
                    'icon'    => '📋'
                ];
            }
        }
    }
} catch (Throwable $e) { }

// Check for completed projects with pending payments (Admin only)
if ($isAdmin) {
    try {
        $stmt = $pdo->query("
            SELECT COUNT(*) 
            FROM projects p 
            WHERE status = 'completed' 
            AND COALESCE(budget, 0) > (
                SELECT COALESCE(SUM(amount), 0) 
                FROM project_payments 
                WHERE project_id = p.id
            )
        ");
        $unpaidCount = (int)$stmt->fetchColumn();
        
        if ($unpaidCount > 0) {
            $response['notifications'][] = [
                'type'    => 'unpaid_projects',
                'title'   => $unpaidCount . ' Απλήρωτα Ολοκληρωμένα Έργα',
                'message' => 'Υπάρχουν έργα που έχουν ολοκληρωθεί αλλά υπάρχει υπόλοιπο πελάτη.',
                'url'     => '/gopools/public/projects/index.php?assistant_filter=unpaid',
                'icon'    => '💳'
            ];
        }
    } catch (Throwable $e) { }
}

// Check expenses if user has permissions
$role = strtolower(trim((string)($user['role'] ?? '')));
if ($role === 'admin' || $role === 'employee' || $role === 'manager') {
    try {
        $stmt = $pdo->query("SELECT COUNT(*) FROM expenses WHERE status = 'pending'");
        $pendingExpensesCount = (int)$stmt->fetchColumn();
        
        if ($pendingExpensesCount > 0) {
            $response['notifications'][] = [
                'type'    => 'expenses',
                'title'   => $pendingExpensesCount . ' Εκκρεμή Έξοδα',
                'message' => 'Υπάρχουν έξοδα που αναμένουν έγκριση.',
                'url'     => '/gopools/public/expenses/index.php',
                'icon'    => '💰'
            ];
        }
    } catch (Throwable $e) { }
}

// Add a default welcome message if no notifications
if (count($response['notifications']) === 0) {
    $response['notifications'][] = [
        'type' => 'info',
        'title' => 'Όλα φαίνονται καλά!',
        'message' => 'Δεν υπάρχουν άμεσες εκκρεμότητες αυτή τη στιγμή.',
        'url' => '#',
        'icon' => '✅'
    ];
}

echo json_encode($response);
