<?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 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"
    ];

    $ch = curl_init($usersUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    $response = curl_exec($ch);

    if ($response === false) {
        echo "Error fetching users: " . curl_error($ch);
        curl_close($ch);
        return null;
    }

    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200) {
        echo "Error fetching users: HTTP Error Code - $httpCode";
        return null;
    }

    $users = json_decode($response, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        echo "Error decoding JSON: " . json_last_error_msg();
        return null;
    }

    return $users;
}

// Function to fetch the job codes from QuickBooks Time API
function getJobCodes($accessToken) {
    $jobcodesUrl = "https://api.tsheets.com/api/v1/jobcodes";
    $headers = [
        "Authorization: Bearer $accessToken",
        "Accept: application/json",
        "Content-Type: application/json",
        "User-Agent: QuickBooks-Integration-Script"
    ];

    $ch = curl_init($jobcodesUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    $response = curl_exec($ch);

    if ($response === false) {
        echo "Error fetching job codes: " . curl_error($ch);
        curl_close($ch);
        return null;
    }

    echo "<h3>All Job Codes JSON:</h3><pre>" . htmlspecialchars($response) . "</pre>";

    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200) {
        echo "Error fetching job codes: HTTP Error Code - $httpCode";
        return null;
    }

    $jobcodes = json_decode($response, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        echo "Error decoding JSON: " . json_last_error_msg();
        return null;
    }

    return $jobcodes;
}

// Function to start a regular timesheet for a specific user onto a specific project
function startRegularTimesheet($accessToken, $userId, $jobcodeId) {
    $start = (new DateTime('now', new DateTimeZone('Australia/Brisbane')))->format('Y-m-d\TH:i:sP');
    $end = ""; // Active on-the-clock timesheet

    // Data to start a regular timesheet
    $regularTimeSheetData = [
        "data" => [
            [
                "user_id" => $userId,
                "jobcode_id" => $jobcodeId,
                "start" => $start,  // Starting time for the timesheet
                "type" => "regular",
                "end" => $end
            ]
        ]
    ];

    $timesheetsUrl = "https://api.tsheets.com/api/v1/timesheets";
    $headers = [
        "Authorization: Bearer $accessToken",
        "Accept: application/json",
        "Content-Type: application/json",
        "User-Agent: QuickBooks-Integration-Script"
    ];

    $ch = curl_init($timesheetsUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    echo "<h3>JSON Sent to API:</h3><pre>" . htmlspecialchars(json_encode($regularTimeSheetData, JSON_PRETTY_PRINT)) . "</pre>";
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($regularTimeSheetData));
    $response = curl_exec($ch);

    // Check for errors in the API response
    if ($response === false) {
        echo "Error starting regular timesheet: " . curl_error($ch);
        curl_close($ch);
        return null;
    }

    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    echo "<h3>API Response:</h3><pre>" . htmlspecialchars($response) . "</pre>";
    curl_close($ch);

    if ($httpCode !== 201) {
        echo "Error starting regular timesheet: HTTP Error Code - $httpCode";
        return null;
    }

    $regularTimeSheetResponse = json_decode($response, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        echo "Error decoding JSON: " . json_last_error_msg();
        return null;
    }

    return $regularTimeSheetResponse;
}

// Fetch users and find the specified employee
$users = getQuickBooksUsers($accessToken);
if ($users && isset($users['results']['users'])) {
    $employeeUserId = null;
    $employeeName = isset($_GET['employee']) ? strtolower($_GET['employee']) : '';
    foreach ($users['results']['users'] as $user) {
        $fullName = strtolower($user['first_name'] . ' ' . $user['last_name']);
        if ($fullName == $employeeName) {
            $employeeUserId = $user['id'];
            break;
        }
    }

    if ($employeeUserId) {
        // Fetch job codes and find the correct one based on the query string parameter "job"
        $jobcodes = getJobCodes($accessToken);
        if ($jobcodes && isset($jobcodes['results']['jobcodes'])) {
            $jobcodeId = null;
            $jobName = isset($_GET['job']) ? strtolower($_GET['job']) : '';
            foreach ($jobcodes['results']['jobcodes'] as $jobcode) {
                if (strtolower($jobcode['name']) == $jobName) {
                    $jobcodeId = $jobcode['id'];
                    break;
                }
            }

            if ($jobcodeId) {
                // Start regular timesheet for the specified employee onto the specified project
                $regularTimeSheetResponse = startRegularTimesheet($accessToken, $employeeUserId, $jobcodeId);
                if ($regularTimeSheetResponse && isset($regularTimeSheetResponse['results']['timesheets'])) {
                    echo "<p>Successfully started regular timesheet for " . htmlspecialchars($employeeName) . " on the '" . htmlspecialchars($jobName) . "' project.</p>";
                    echo "<h3>Final API Response:</h3><pre>" . htmlspecialchars(json_encode($regularTimeSheetResponse, JSON_PRETTY_PRINT)) . "</pre>";
                } else {
                    echo "<p>Failed to start regular timesheet for " . htmlspecialchars($employeeName) . "</p>";
                }
            } else {
                echo "<p>Job code for '" . htmlspecialchars($jobName) . "' not found.</p>";
            }
        } else {
            echo "<p>Error fetching job codes.</p>";
        }
    } else {
        echo "<p>User " . htmlspecialchars($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>";

?>