<?php

function apply_reward(PDO $pdo, int $sp_company_id, int $breakdown_id, string $reason, int $points = 1)
{
    /* Log reward */
    $stmt = $pdo->prepare("
        INSERT INTO sp_reward_log (sp_company_id, breakdown_id, reason, reward_points)
        VALUES (?, ?, ?, ?)
    ");
    $stmt->execute([$sp_company_id, $breakdown_id, $reason, $points]);

    /* Increment company total */
    $stmt = $pdo->prepare("
        UPDATE companies
        SET reward_points = reward_points + ?
        WHERE id = ?
    ");
    $stmt->execute([$points, $sp_company_id]);
}

function evaluate_rewards(PDO $pdo, int $sp_company_id, int $breakdown_id, array $b): void
{
    if ($b['allocated_at'] && $b['broadcast_started_at']) {
        $accept = (strtotime($b['allocated_at']) - strtotime($b['broadcast_started_at'])) / 60;
        if ($accept <= 5) {
            apply_reward($pdo, $sp_company_id, $breakdown_id, 'Fast acceptance', 1);
        }
    }

    if ($b['allocated_at'] && $b['started_at']) {
        $dispatch = (strtotime($b['started_at']) - strtotime($b['allocated_at'])) / 60;
        if ($dispatch <= 5) {
            apply_reward($pdo, $sp_company_id, $breakdown_id, 'Fast dispatch', 1);
        }
    }

    if ($b['started_at'] && $b['arrived_at']) {
        $travel = (strtotime($b['arrived_at']) - strtotime($b['started_at'])) / 60;
        $limit = ((int)$b['tier_level']) * 30;
        if ($travel <= ($limit * 0.75)) {
            apply_reward($pdo, $sp_company_id, $breakdown_id, 'Efficient travel', 1);
        }
    }

    if ($b['arrived_at']) {
        $repair = (time() - strtotime($b['arrived_at'])) / 60;
        if ($repair <= 60) {
            apply_reward($pdo, $sp_company_id, $breakdown_id, 'Fast repair', 1);
        }
    }
}