<?php
require_once 'config.php';
require_once 'includes/Database.php';
require_once 'includes/Auth.php';

Auth::requireLogin();

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

// Hata raporlamayı aç (geliştirme için)
error_reporting(E_ALL);
ini_set('display_errors', 0); // JSON için ekrana yazma
ini_set('log_errors', 1);

$db = new Database();

$representative = $_GET['representative'] ?? '';
$startDate = $_GET['start_date'] ?? '';
$endDate = $_GET['end_date'] ?? '';

if (empty($representative) || empty($startDate) || empty($endDate)) {
    echo json_encode(['success' => false, 'message' => 'Eksik parametreler']);
    exit;
}

try {
    // Kriterleri çek
    $criteria = $db->fetchAll("
        SELECT id, name, code, category, point_value
        FROM criteria
        WHERE is_active = 1
        ORDER BY category ASC, name ASC
    ");

    // Seçilen tarih aralığı için ortadaki tarihi hesapla (tarihçe kontrolü için)
    $startTimestamp = strtotime($startDate);
    $endTimestamp = strtotime($endDate);
    $middleTimestamp = $startTimestamp + (($endTimestamp - $startTimestamp) / 2);
    $referenceDate = date('Y-m-d', $middleTimestamp);

    $criteriaPoints = [];
    foreach ($criteria as $crit) {
        $baseValue = floatval($crit['point_value']);

        // Tarihçede bu tarih için özel değer var mı kontrol et
        $historyValue = $db->fetchOne("
            SELECT point_value
            FROM criteria_history
            WHERE criteria_code = ?
              AND start_date <= ?
              AND (end_date IS NULL OR end_date >= ?)
            ORDER BY start_date DESC
            LIMIT 1
        ", [$crit['code'], $referenceDate, $referenceDate]);

        // Eğer tarihçede değer varsa onu kullan, yoksa varsayılanı kullan
        $criteriaPoints[$crit['code']] = ($historyValue && isset($historyValue['point_value']))
            ? floatval($historyValue['point_value'])
            : $baseValue;
    }

    // Prim tutarını al (tarihçe kontrolü ile)
    $primTutariRow = $db->fetchOne("SELECT point_value FROM criteria WHERE code = 'prim_tutari' AND is_active = 1");
    $basePrimTutari = $primTutariRow['point_value'] ?? 0;

    // Tarihçede prim_tutari için özel değer var mı kontrol et
    $primTutariHistory = $db->fetchOne("
        SELECT point_value
        FROM criteria_history
        WHERE criteria_code = 'prim_tutari'
          AND start_date <= ?
          AND (end_date IS NULL OR end_date >= ?)
        ORDER BY start_date DESC
        LIMIT 1
    ", [$referenceDate, $referenceDate]);

    $primTutari = ($primTutariHistory && isset($primTutariHistory['point_value']))
        ? floatval($primTutariHistory['point_value'])
        : $basePrimTutari;

    // Önce user_id'yi bul
    $user = $db->fetchOne("
        SELECT id, full_name
        FROM users
        WHERE full_name = ?
        AND is_active = 1
    ", [$representative]);

    if (!$user) {
        throw new Exception('Kullanıcı bulunamadı');
    }

    $userId = $user['id'];

    // 1. GELEN ARAMALAR
    $incomingData = $db->fetchOne("
        SELECT
            COALESCE(SUM(answered_count), 0) as total_calls,
            COALESCE(SUM(TIME_TO_SEC(total_duration)), 0) as total_duration_seconds
        FROM incoming_calls
        WHERE user_id = ?
        AND call_date BETWEEN ? AND ?
    ", [$userId, $startDate, $endDate]);

    $incomingCalls = (int)($incomingData['total_calls'] ?? 0);
    $incomingDuration = (int)($incomingData['total_duration_seconds'] ?? 0);

    // 2. GİDEN ARAMALAR
    $outgoingData = $db->fetchOne("
        SELECT
            COALESCE(SUM(answered_count), 0) as total_calls,
            COALESCE(SUM(TIME_TO_SEC(total_duration)), 0) as total_duration_seconds
        FROM outgoing_calls
        WHERE user_id = ?
        AND call_date BETWEEN ? AND ?
    ", [$userId, $startDate, $endDate]);

    $outgoingCalls = (int)($outgoingData['total_calls'] ?? 0);
    $outgoingDuration = (int)($outgoingData['total_duration_seconds'] ?? 0);

    // 3. EĞİTİM KAYITLARI
    $trainings = $db->fetchAll("
        SELECT *
        FROM training_completion
        WHERE support_representative = ?
        AND training_completion_date BETWEEN ? AND ?
        ORDER BY training_completion_date DESC
    ", [$representative, $startDate, $endDate]);

    // Paket sayılarını topla
    $packageCounts = [];
    foreach ($trainings as $training) {
        $pkgType = $training['package_type'];
        if (!isset($packageCounts[$pkgType])) {
            $packageCounts[$pkgType] = 0;
        }
        $packageCounts[$pkgType]++;
    }

    // PUAN HESAPLAMALARI (bonus.php'deki mantıkla aynı)

    // Tüm personeller için toplamları hesapla (bonus.php'deki mantıkla aynı)
    $allPersonnel = $db->fetchAll("
        SELECT id, full_name
        FROM users
        WHERE is_active = 1
    ");

    $totals = [
        'total_incoming_calls' => 0,
        'total_incoming_duration' => 0,
        'total_outgoing_calls' => 0,
        'total_outgoing_duration' => 0
    ];

    foreach ($allPersonnel as $person) {
        // Mustafa SÜLERYA'yı atla
        if (stripos($person['full_name'], 'Mustafa') !== false && stripos($person['full_name'], 'SÜLERYA') !== false) {
            continue;
        }

        // Bu personelin gelen aramalarını topla
        $personIncoming = $db->fetchOne("
            SELECT
                COALESCE(SUM(answered_count), 0) as total_answered,
                COALESCE(SUM(TIME_TO_SEC(total_duration)), 0) as total_duration_seconds
            FROM incoming_calls
            WHERE user_id = ?
            AND call_date BETWEEN ? AND ?
        ", [$person['id'], $startDate, $endDate]);

        $totals['total_incoming_calls'] += (int)($personIncoming['total_answered'] ?? 0);
        $totals['total_incoming_duration'] += (int)($personIncoming['total_duration_seconds'] ?? 0);

        // Bu personelin giden aramalarını topla
        $personOutgoing = $db->fetchOne("
            SELECT
                COALESCE(SUM(answered_count), 0) as total_answered,
                COALESCE(SUM(TIME_TO_SEC(total_duration)), 0) as total_duration_seconds
            FROM outgoing_calls
            WHERE user_id = ?
            AND call_date BETWEEN ? AND ?
        ", [$person['id'], $startDate, $endDate]);

        $totals['total_outgoing_calls'] += (int)($personOutgoing['total_answered'] ?? 0);
        $totals['total_outgoing_duration'] += (int)($personOutgoing['total_duration_seconds'] ?? 0);
    }

    // Gelen Arama Sayısı puanı
    $scoreIncomingCalls = $totals['total_incoming_calls'] > 0
        ? ($incomingCalls / $totals['total_incoming_calls']) * ($criteriaPoints['gelen_arama_sayisi'] ?? 0)
        : 0;

    // Gelen Arama Süresi puanı
    $scoreIncomingDuration = $totals['total_incoming_duration'] > 0
        ? ($incomingDuration / $totals['total_incoming_duration']) * ($criteriaPoints['gelen_arama_suresi'] ?? 0)
        : 0;

    // Giden Arama Sayısı puanı
    $scoreOutgoingCalls = $totals['total_outgoing_calls'] > 0
        ? ($outgoingCalls / $totals['total_outgoing_calls']) * ($criteriaPoints['giden_arama_sayisi'] ?? 0)
        : 0;

    // Giden Arama Süresi puanı
    $scoreOutgoingDuration = $totals['total_outgoing_duration'] > 0
        ? ($outgoingDuration / $totals['total_outgoing_duration']) * ($criteriaPoints['giden_arama_suresi'] ?? 0)
        : 0;

    // Paket puanları hesaplama için bonus.php'deki mantığı kullan
    $proportionalPackages = [
        'Profesyonel Paket' => 1.0,
        'Gelişmiş Paket' => 1.0,
        'Uzman Paket' => 1.0,
        'Ideasoft Mini 2' => 1.0,
        'Ideasoft Mini 3' => 1.0,
        'Ideasoft Maksi' => 1.0,
        'Ideasoft ERP' => 0.5
    ];

    $bonusPackages = [
        'Sopyo Logo' => 1.0,
        'Sopyo Nebim' => 1.0,
        'Sopyo Nebim v3' => 1.0,
        'Lisans Yenileme' => 0.25,
        'Google Yorum' => 1.0
    ];

    // Bu personelin oransal ve bonus paketlerini hesapla
    $proportionalWeighted = 0;
    $proportionalDetails = [];
    $bonusTotal = 0;
    $bonusDetails = [];

    foreach ($packageCounts as $pkgType => $count) {
        foreach ($proportionalPackages as $pkgName => $weight) {
            if (stripos($pkgType, $pkgName) !== false || stripos($pkgName, $pkgType) !== false) {
                $weighted = $count * $weight;
                $proportionalWeighted += $weighted;
                $proportionalDetails[] = [
                    'name' => $pkgType,
                    'count' => $count,
                    'weight' => $weight,
                    'weighted' => $weighted
                ];
                break;
            }
        }

        foreach ($bonusPackages as $pkgName => $point) {
            if (stripos($pkgType, $pkgName) !== false || stripos($pkgName, $pkgType) !== false) {
                $pkgBonus = $count * $point;
                $bonusTotal += $pkgBonus;
                $bonusDetails[] = [
                    'name' => $pkgType,
                    'count' => $count,
                    'point' => $point,
                    'total' => $pkgBonus
                ];
                break;
            }
        }
    }

    // Toplam oransal ağırlık hesaplama - bonus.php'deki AYNI mantıkla
    // Yukarıda tanımlanan $allPersonnel değişkenini kullan
    $totalProportionalWeighted = 0;

    foreach ($allPersonnel as $person) {
        $personName = $person['full_name'];

        // Mustafa SÜLERYA'yı atla
        if (stripos($personName, 'Mustafa') !== false && stripos($personName, 'SÜLERYA') !== false) {
            continue;
        }

        // Bu personelin paketlerini çek (GROUP BY ile - bonus.php'deki gibi)
        $personTrainingStats = $db->fetchAll("
            SELECT
                package_type,
                COUNT(*) as count
            FROM training_completion
            WHERE support_representative = ?
            AND training_completion_date BETWEEN ? AND ?
            GROUP BY package_type
        ", [$personName, $startDate, $endDate]);

        // Her paket türü için ağırlıklı hesaplama
        foreach ($personTrainingStats as $stat) {
            $pkgType = $stat['package_type'];
            $count = (int)$stat['count'];

            foreach ($proportionalPackages as $pkgName => $weight) {
                if (stripos($pkgType, $pkgName) !== false || stripos($pkgName, $pkgType) !== false) {
                    $totalProportionalWeighted += $count * $weight;
                    break;
                }
            }
        }
    }

    // Oransal paket puanını hesapla (bonus.php'deki mantıkla aynı)
    $egitimOraniValue = floatval($criteriaPoints['egitim_orani'] ?? 0);
    $scoreProportionalPackages = $totalProportionalWeighted > 0
        ? (floatval($proportionalWeighted) / floatval($totalProportionalWeighted)) * $egitimOraniValue
        : 0;

    $scoreBonusPackages = $bonusTotal;

    // Toplam puan
    $totalScore = $scoreIncomingCalls + $scoreIncomingDuration +
                  $scoreOutgoingCalls + $scoreOutgoingDuration +
                  $scoreProportionalPackages + $scoreBonusPackages;

    // Maksimum teorik puan
    $maxTheoreticalScore = ($criteriaPoints['gelen_arama_sayisi'] ?? 0) +
                           ($criteriaPoints['gelen_arama_suresi'] ?? 0) +
                           ($criteriaPoints['giden_arama_sayisi'] ?? 0) +
                           ($criteriaPoints['giden_arama_suresi'] ?? 0) +
                           ($criteriaPoints['egitim_orani'] ?? 0);

    // Puan yüzdesi
    $scorePercentage = $maxTheoreticalScore > 0 ? ($totalScore / $maxTheoreticalScore) * 100 : 0;

    // NOT: Gerçek prim tutarını hesaplamak için bonus.php'deki tüm mantığı tekrarlamak gerekir
    // Şimdilik basitleştirilmiş hesaplama
    $bonusAmount = 0; // Bu değer frontend'de gösterilecek ama tam doğru olmayabilir

    echo json_encode([
        'success' => true,
        'representative' => $representative,
        'start_date' => $startDate,
        'end_date' => $endDate,
        'trainings' => $trainings,
        'package_counts' => $packageCounts,
        'scores' => [
            'incoming_calls' => $scoreIncomingCalls,
            'incoming_duration' => $scoreIncomingDuration,
            'outgoing_calls' => $scoreOutgoingCalls,
            'outgoing_duration' => $scoreOutgoingDuration,
            'proportional_packages' => $scoreProportionalPackages,
            'bonus_packages' => $scoreBonusPackages,
            'total_score' => $totalScore,
            'score_percentage' => $scorePercentage
        ],
        'raw_data' => [
            'incoming_calls' => $incomingCalls,
            'incoming_duration' => $incomingDuration,
            'outgoing_calls' => $outgoingCalls,
            'outgoing_duration' => $outgoingDuration
        ],
        'package_details' => [
            'proportional' => $proportionalDetails,
            'bonus' => $bonusDetails,
            'proportional_weighted_total' => $proportionalWeighted,
            'total_proportional_weighted' => $totalProportionalWeighted
        ],
        'criteria_points' => $criteriaPoints,
        'max_theoretical_score' => $maxTheoreticalScore,
        'prim_tutari' => $primTutari,
        'bonus_amount' => $bonusAmount // Bu değer tam doğru olmayabilir
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'file' => $e->getFile(),
        'line' => $e->getLine(),
        'trace' => $e->getTraceAsString()
    ]);
}
?>
