<?php
include "$_SERVER[DOCUMENT_ROOT]/root.class.php";
include "$_SERVER[DOCUMENT_ROOT]/app/team_dashboard/classes/team_dashboard.class.php";
$db = new db_safeguard();
$team = new TeamDashboard($db);

$team_id = intval($_GET['team_id']);

/* GET USERS */
$users_res = $db->query(
    "users",
    "SELECT record_id FROM users WHERE team_id='$team_id'"
);

$user_ids = [];
while ($u = $users_res->fetch_assoc()) {
    $user_ids[] = $u['record_id'];
}
if (empty($user_ids))
    exit;

$user_sql = implode(",", $user_ids);

/* GET JOBCARDS */
$jobcards = $db->query(
    "jobcard_timeline",
    "SELECT DISTINCT jobcard_id FROM jobcard_timeline WHERE user_id IN ($user_sql)"
);

$output = [];

while ($jc = $jobcards->fetch_assoc()) {
    $jobcard_id = $jc['jobcard_id'];

    $timeline = $db->query(
        "jobcard_timeline",
        "SELECT type,date_time FROM jobcard_timeline
         WHERE jobcard_id='$jobcard_id'
         AND type NOT IN ('DEPARTURE','ARRIVED')
         ORDER BY record_id ASC"
    );

    $total_seconds = 0;
    $riem = $drill = $casing = null;

    while ($row = $timeline->fetch_assoc()) {
        switch ($row['type']) {
            case 'RIEM_START':
            case 'RIEMING_START':
                $riem = strtotime($row['date_time']);
                break;

            case 'RIEM_STOP':
            case 'RIEMING_STOP':
                if ($riem) {
                    $total_seconds += strtotime($row['date_time']) - $riem;
                    $riem = null;
                }
                break;

            case 'DRILLING_START':
                $drill = strtotime($row['date_time']);
                break;

            case 'DRILLING_STOP':
                if ($drill) {
                    $total_seconds += strtotime($row['date_time']) - $drill;
                    $drill = null;
                }
                break;

            case 'CASING_START':
                $casing = strtotime($row['date_time']);
                break;

            case 'CASING_STOP':
                if ($casing) {
                    $total_seconds += strtotime($row['date_time']) - $casing;
                    $casing = null;
                }
                break;
        }
    }

    if ($total_seconds > 0) {
        $hours = round($total_seconds / 3600, 2);
        $output[] = "$jobcard_id,$hours";
    }
}

echo implode("|", $output);