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

Auth::requireLogin();

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

$db = new Database();

try {
    $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;
    }

    // Personelin eğitimlerini getir
    $trainings = $db->fetchAll("
        SELECT
            company_id,
            company_name,
            package_type,
            sales_type,
            training_completion_date,
            sales_source
        FROM training_completion
        WHERE support_representative = ?
            AND training_completion_date IS NOT NULL
            AND training_completion_date BETWEEN ? AND ?
        ORDER BY training_completion_date DESC
    ", [$representative, $startDate, $endDate]);

    // İstatistikleri hesapla
    $totalTrainings = count($trainings);
    $uniqueCompanies = count(array_unique(array_column($trainings, 'company_id')));

    echo json_encode([
        'success' => true,
        'trainings' => $trainings,
        'total_trainings' => $totalTrainings,
        'unique_companies' => $uniqueCompanies
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Bir hata oluştu: ' . $e->getMessage()
    ]);
}
?>
