<?php
ini_set('max_execution_time', '600');
define("BASEPATH", TRUE);
require $_SERVER["DOCUMENT_ROOT"]."/vendor/autoload.php";
require $_SERVER["DOCUMENT_ROOT"]."/app/init.php";
require $_SERVER["DOCUMENT_ROOT"]."/core/bootstrap.php";

$to = 9;  // Number of recent orders to consider

// Fetch all services
$services = $conn->prepare("SELECT * FROM services");
$services->execute();
$services = $services->fetchAll(PDO::FETCH_ASSOC);

foreach ($services as $service) {
    // Fetch recent completed orders for the service with quantity 1000
    $orders = $conn->prepare("SELECT * FROM orders 
        WHERE order_status = :status 
        AND order_quantity = :quantity 
        AND service_id = :id 
        ORDER BY order_id DESC 
        LIMIT $to");
    $orders->execute(array("quantity" => "1000", "status" => "completed", "id" => $service["service_id"]));
    $orders = $orders->fetchAll(PDO::FETCH_ASSOC);

    if (count($orders) == 0) {
        continue; // Skip to the next service if there are no orders
    }

    // Calculate average time for the service based on orders
    $totalTime = 0;
    $orderCount = count($orders);

    foreach ($orders as $order) {
        $timestamp1 = strtotime($order["order_create"]);
        $timestamp2 = strtotime($order["last_check"]);
        $totalTime += abs($timestamp2 - $timestamp1);
    }

    $averageTime = $totalTime / $orderCount;

    // Convert average time from seconds to hours and minutes
    $hours = floor($averageTime / 3600);
    $minutes = floor(($averageTime % 3600) / 60);

    $average = "$hours hours and $minutes minutes";
    if ($hours == 0) $average = "$minutes Minutes";
    if ($minutes == 0) $average = "$hours Hours";
    if ($hours == 0 && $minutes == 0) $average = "Not enough data";
    if ($hours == 0 && $minutes == 1) $average = "$minutes Minute";
    if ($hours == 1 && $minutes == 0) $average = "$hours Hour";

    // Update service time
    $update = $conn->prepare("UPDATE services SET time = :time WHERE service_id = :id");
    $update->execute(array("id" => $service["service_id"], "time" => $average));
}
?>
