<?php
require_once 'config.php';

try {
    $pdo = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4', DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Sütunların var olup olmadığını kontrol et
    $stmt = $pdo->query('DESCRIBE outgoing_calls');
    $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    $hasAnsweredCount = in_array('answered_count', $columns);
    $hasUnansweredCount = in_array('unanswered_count', $columns);
    $hasAnswerPercentage = in_array('answer_percentage', $columns);
    
    if (!$hasAnsweredCount) {
        $pdo->exec('ALTER TABLE outgoing_calls ADD COLUMN answered_count INT DEFAULT 0 AFTER call_count');
        echo 'answered_count sütunu eklendi.' . PHP_EOL;
    } else {
        echo 'answered_count sütunu zaten mevcut.' . PHP_EOL;
    }
    
    if (!$hasUnansweredCount) {
        $pdo->exec('ALTER TABLE outgoing_calls ADD COLUMN unanswered_count INT DEFAULT 0 AFTER answered_count');
        echo 'unanswered_count sütunu eklendi.' . PHP_EOL;
    } else {
        echo 'unanswered_count sütunu zaten mevcut.' . PHP_EOL;
    }
    
    if (!$hasAnswerPercentage) {
        $pdo->exec('ALTER TABLE outgoing_calls ADD COLUMN answer_percentage DECIMAL(5, 2) DEFAULT 0.00 AFTER unanswered_count');
        echo 'answer_percentage sütunu eklendi.' . PHP_EOL;
    } else {
        echo 'answer_percentage sütunu zaten mevcut.' . PHP_EOL;
    }
    
    // Mevcut verileri güncelle (eğer answered_count ve unanswered_count 0 ise)
    $updateResult = $pdo->exec("
        UPDATE outgoing_calls 
        SET answered_count = call_count,
            unanswered_count = 0,
            answer_percentage = 100.00
        WHERE answered_count = 0 AND unanswered_count = 0 AND call_count > 0
    ");
    
    if ($updateResult > 0) {
        echo "Mevcut $updateResult kayıt güncellendi." . PHP_EOL;
    }
    
    echo 'Veritabanı güncelleme tamamlandı!' . PHP_EOL;
    
} catch (Exception $e) {
    echo 'Hata: ' . $e->getMessage() . PHP_EOL;
}
?>
