<?php

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// QuickBooks Time API Access Token
$accessToken = "S.6__fc9fd0aa62de30aece79e5d94412b31dbee1614a";

// Track the start time
$startTime = microtime(true);

// Function to make a cURL request
function makeCurlRequest($url, $headers, $method = "GET", $data = null) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    if ($data) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    }
    $response = curl_exec($ch);
    if ($response === false) {
        echo "cURL Error: " . curl_error($ch);
        curl_close($ch);
        return null;
    }
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($httpCode < 200 || $httpCode >= 300) {
        echo "HTTP Error Code: $httpCode";
        echo "<h3>API Response:</h3><pre>" . htmlspecialchars($response) . "</pre>";
        return null;
    }
    $decodedResponse = json_decode($response, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        echo "Error decoding JSON: " . json_last_error_msg();
        return null;
    }
    return $decodedResponse;
}

// Function to fetch list of users from QuickBooks Time API
function getQuickBooksUsers($accessToken) {
    $usersUrl = "https://api.tsheets.com/api/v1/users";
    $headers = [
        "Authorization: Bearer $accessToken",
        "Accept: application/json",
        "Content-Type: application/json",
        "User-Agent: QuickBooks-Integration-Script"
    ];
    return makeCurlRequest($usersUrl, $headers);
}

// Function to fetch the active timesheet for a user
function getActiveTimesheet($accessToken, $userId) {
    $startDate = (new DateTime('-1 day', new DateTimeZone('Australia/Brisbane')))->format('Y-m-d');
    $timesheetsUrl = "https://api.tsheets.com/api/v1/timesheets?user_ids=$userId&on_the_clock=true&start_date=$startDate";
    $headers = [
        "Authorization: Bearer $accessToken",
        "Accept: application/json",
        "Content-Type: application/json",
        "User-Agent: QuickBooks-Integration-Script"
    ];
    return makeCurlRequest($timesheetsUrl, $headers);
}

// Function to end a timesheet
function endTimesheet($accessToken, $timesheetId) {
    $end = (new DateTime('now', new DateTimeZone('Australia/Brisbane')))->format('Y-m-d\TH:i:sP');
    $timesheetsUrl = "https://rest.tsheets.com/api/v1/timesheets";
    $headers = [
        "Authorization: Bearer $accessToken",
        "Accept: application/json",
        "Content-Type: application/json",
        "User-Agent: QuickBooks-Integration-Script"
    ];
    $updateData = [
        "data" => [
            [
                "id" => $timesheetId,
                "end" => $end
            ]
        ]
    ];
    echo "<h3>JSON Sent to End Timesheet API:</h3><pre>" . htmlspecialchars(json_encode($updateData, JSON_PRETTY_PRINT)) . "</pre>";
    return makeCurlRequest($timesheetsUrl, $headers, "PUT", $updateData);
}

if (!isset($_GET['employee'])) {
    echo "<p>Error: Employee name must be specified in the query string as 'employee'.</p>";
    exit;
}

$employeeName = strtolower(trim($_GET['employee']));

// Fetch users and find $employeeName
$users = getQuickBooksUsers($accessToken);
if ($users && isset($users['results']['users'])) {
    $employeeUserId = null;
    foreach ($users['results']['users'] as $user) {
        if (strcasecmp($user['first_name'] . ' ' . $user['last_name'], $employeeName) == 0) {
            $employeeUserId = $user['id'];
            break;
        }
    }

    if ($employeeUserId) {
        // Fetch active timesheet for the employee
        $activeTimesheet = getActiveTimesheet($accessToken, $employeeUserId);
        if ($activeTimesheet && isset($activeTimesheet['results']['timesheets']) && count($activeTimesheet['results']['timesheets']) > 0) {
            echo "<h3>Active Timesheet Details:</h3><pre>" . htmlspecialchars(json_encode($activeTimesheet, JSON_PRETTY_PRINT)) . "</pre>";
            $timesheets = array_values($activeTimesheet['results']['timesheets']);
            $timesheetId = $timesheets[0]['id'];
            // End the active timesheet
            $endTimesheetResponse = endTimesheet($accessToken, $timesheetId);
            if ($endTimesheetResponse && isset($endTimesheetResponse['results']['timesheets'])) {
                echo "<p>Successfully ended timesheet for $employeeName.</p>";
                echo "<h3>Final API Response:</h3><pre>" . htmlspecialchars(json_encode($endTimesheetResponse, JSON_PRETTY_PRINT)) . "</pre>";
            } else {
                echo "<p>Failed to end timesheet for $employeeName.</p>";
            }
        } else {
            echo "<p>No active timesheet found for $employeeName.</p>";
        }
    } else {
        echo "<p>User $employeeName not found.</p>";
    }
} else {
    echo "<p>Error fetching users.</p>";
}

// Calculate the total time taken to execute the operation
$endTime = microtime(true);
$executionTime = round($endTime - $startTime, 2);
echo "<p id='dataSourcingTime' class='center-align'>Operation took $executionTime seconds.</p>";

?>