<?php
session_start();
require_once '../inc/config.php';
require_once '../inc/functions.php';

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

// Check if user is logged in and has permission
if (!isset($_SESSION['user_id']) || !has_permission('bonuses_manage')) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Yetkisiz erişim']);
    exit();
}

$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($method) {
        case 'POST':
            // Add new cashback program
            $program_name = $_POST['program_name'] ?? '';
            $cashback_percentage = $_POST['cashback_percentage'] ?? 0;
            $min_loss_amount = $_POST['min_loss_amount'] ?? 0;
            $max_cashback_amount = $_POST['max_cashback_amount'] ?? 0;
            $status = $_POST['status'] ?? 'active';
            $validity_days = $_POST['validity_days'] ?? 7;
            $description = $_POST['description'] ?? '';

            if (empty($program_name) || $cashback_percentage <= 0) {
                throw new Exception('Gerekli alanlar eksik veya geçersiz');
            }

            $stmt = $pdo->prepare("INSERT INTO cashback_programs (program_name, cashback_percentage, min_loss_amount, max_cashback_amount, status, validity_days, description, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
            $stmt->execute([$program_name, $cashback_percentage, $min_loss_amount, $max_cashback_amount, $status, $validity_days, $description]);

            // Log the action
            log_admin_action($_SESSION['user_id'], 'cashback_program_add', "Added cashback program: $program_name");

            echo json_encode(['success' => true, 'message' => 'Cashback programı başarıyla eklendi']);
            break;

        case 'PUT':
            // Update cashback program
            $input = json_decode(file_get_contents('php://input'), true);
            $id = $input['id'] ?? 0;
            $program_name = $input['program_name'] ?? '';
            $cashback_percentage = $input['cashback_percentage'] ?? 0;
            $min_loss_amount = $input['min_loss_amount'] ?? 0;
            $max_cashback_amount = $input['max_cashback_amount'] ?? 0;
            $status = $input['status'] ?? 'active';
            $validity_days = $input['validity_days'] ?? 7;
            $description = $input['description'] ?? '';

            if (!$id || empty($program_name)) {
                throw new Exception('Geçersiz veri');
            }

            $stmt = $pdo->prepare("UPDATE cashback_programs SET program_name = ?, cashback_percentage = ?, min_loss_amount = ?, max_cashback_amount = ?, status = ?, validity_days = ?, description = ? WHERE id = ?");
            $stmt->execute([$program_name, $cashback_percentage, $min_loss_amount, $max_cashback_amount, $status, $validity_days, $description, $id]);

            // Log the action
            log_admin_action($_SESSION['user_id'], 'cashback_program_update', "Updated cashback program ID: $id");

            echo json_encode(['success' => true, 'message' => 'Cashback programı başarıyla güncellendi']);
            break;

        case 'DELETE':
            // Delete cashback program
            $input = json_decode(file_get_contents('php://input'), true);
            $id = $input['id'] ?? 0;

            if (!$id) {
                throw new Exception('Geçersiz ID');
            }

            // Check if program has payments
            $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM cashback_payments WHERE program_id = ?");
            $stmt->execute([$id]);
            $payments = $stmt->fetch()['count'];

            if ($payments > 0) {
                throw new Exception('Bu programa ait ödemeler var, silinemez');
            }

            $stmt = $pdo->prepare("DELETE FROM cashback_programs WHERE id = ?");
            $stmt->execute([$id]);

            // Log the action
            log_admin_action($_SESSION['user_id'], 'cashback_program_delete', "Deleted cashback program ID: $id");

            echo json_encode(['success' => true, 'message' => 'Cashback programı başarıyla silindi']);
            break;

        case 'GET':
            // Get cashback program details or process cashback
            $action = $_GET['action'] ?? '';
            
            if ($action === 'process_cashback') {
                // Process automatic cashback for eligible users
                $processed = processCashback();
                echo json_encode(['success' => true, 'message' => "$processed kullanıcı için cashback işlendi"]);
            } else {
                $id = $_GET['id'] ?? 0;

                if (!$id) {
                    throw new Exception('Geçersiz ID');
                }

                $stmt = $pdo->prepare("SELECT * FROM cashback_programs WHERE id = ?");
                $stmt->execute([$id]);
                $program = $stmt->fetch();

                if (!$program) {
                    throw new Exception('Program bulunamadı');
                }

                echo json_encode(['success' => true, 'data' => $program]);
            }
            break;

        default:
            throw new Exception('Geçersiz HTTP metodu');
    }

} catch (Exception $e) {
    error_log("Cashback API Error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

function processCashback() {
    global $pdo;
    
    try {
        // Get active cashback programs
        $stmt = $pdo->prepare("SELECT * FROM cashback_programs WHERE status = 'active'");
        $stmt->execute();
        $programs = $stmt->fetchAll();
        
        $processed_count = 0;
        
        foreach ($programs as $program) {
            // Find users eligible for cashback (users with losses in the last validity period)
            $validity_date = date('Y-m-d H:i:s', strtotime("-{$program['validity_days']} days"));
            
            $stmt = $pdo->prepare("
                SELECT u.id as user_id, 
                       SUM(CASE WHEN t.result = 'loss' THEN t.amount ELSE 0 END) as total_loss
                FROM users u 
                JOIN transactions t ON u.id = t.user_id 
                WHERE t.created_at >= ? 
                  AND t.type = 'bet' 
                  AND t.result = 'loss'
                  AND u.id NOT IN (
                      SELECT user_id FROM cashback_payments 
                      WHERE program_id = ? AND created_at >= ?
                  )
                GROUP BY u.id 
                HAVING total_loss >= ?
            ");
            
            $stmt->execute([$validity_date, $program['id'], $validity_date, $program['min_loss_amount']]);
            $eligible_users = $stmt->fetchAll();
            
            foreach ($eligible_users as $user) {
                $cashback_amount = ($user['total_loss'] * $program['cashback_percentage']) / 100;
                
                // Apply maximum cashback limit
                if ($cashback_amount > $program['max_cashback_amount']) {
                    $cashback_amount = $program['max_cashback_amount'];
                }
                
                // Insert cashback payment
                $stmt = $pdo->prepare("
                    INSERT INTO cashback_payments 
                    (user_id, program_id, loss_amount, cashback_amount, status, created_at) 
                    VALUES (?, ?, ?, ?, 'paid', NOW())
                ");
                $stmt->execute([$user['user_id'], $program['id'], $user['total_loss'], $cashback_amount]);
                
                // Add cashback to user balance
                $stmt = $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
                $stmt->execute([$cashback_amount, $user['user_id']]);
                
                // Log transaction
                $stmt = $pdo->prepare("
                    INSERT INTO transactions 
                    (user_id, type, amount, description, status, created_at) 
                    VALUES (?, 'cashback', ?, ?, 'completed', NOW())
                ");
                $stmt->execute([$user['user_id'], $cashback_amount, "Cashback: {$program['program_name']}"]);
                
                $processed_count++;
            }
        }
        
        return $processed_count;
        
    } catch (Exception $e) {
        error_log("Process Cashback Error: " . $e->getMessage());
        return 0;
    }
}
?>