<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");

header("Content-Type: application/json");

$pdo = db_connect();
$car_number = $_GET['car_number'] ?? '';
$num = $_GET['num'] ?? '';

if (!$car_number) {
    echo json_encode(['error' => '차량번호가 제공되지 않았습니다.']);
    exit;
}

$current_month = date('Y-m-01'); // 현재 월의 시작일

try {
    // 1. 최초 주행거리 가져오기
    $initial_sql = "SELECT IFNULL(initial_distance, 0) as initial_distance FROM " . $DB . ".juilcar WHERE vehicle_number = ? AND is_deleted IS NULL";
    $initial_stmh = $pdo->prepare($initial_sql);
    $initial_stmh->bindValue(1, $car_number, PDO::PARAM_STR);
    $initial_stmh->execute();
    $initial_result = $initial_stmh->fetch(PDO::FETCH_ASSOC);
    $initial_distance = floatval($initial_result['initial_distance'] ?? 0);

    // 2. 현재 월의 주행거리 합계 가져오기 (월간 누적거리)
    $monthly_sql = "SELECT SUM(driving_distance) as monthly_distance FROM " . $DB . ".juilcarlog 
                    WHERE car_number = ? AND use_date >= ? AND is_deleted = 0";

    if (!empty($num)) {
        $monthly_sql .= " AND num < ?";
    }

    $monthly_stmh = $pdo->prepare($monthly_sql);
    $monthly_stmh->bindValue(1, $car_number, PDO::PARAM_STR);
    $monthly_stmh->bindValue(2, $current_month, PDO::PARAM_STR);

    if (!empty($num)) {
        $monthly_stmh->bindValue(3, $num, PDO::PARAM_INT);
    }

    $monthly_stmh->execute();
    $monthly_result = $monthly_stmh->fetch(PDO::FETCH_ASSOC);
    $monthly_distance = floatval($monthly_result['monthly_distance'] ?? 0);

    // 3. 모든 운행거리 합계 가져오기 (총 누적거리용)
    $total_sql = "SELECT SUM(driving_distance) as total_driving_distance FROM " . $DB . ".juilcarlog 
                  WHERE car_number = ? AND is_deleted = 0";

    if (!empty($num)) {
        $total_sql .= " AND num < ?";
    }

    $total_stmh = $pdo->prepare($total_sql);
    $total_stmh->bindValue(1, $car_number, PDO::PARAM_STR);

    if (!empty($num)) {
        $total_stmh->bindValue(2, $num, PDO::PARAM_INT);
    }

    $total_stmh->execute();
    $total_result = $total_stmh->fetch(PDO::FETCH_ASSOC);
    $total_driving_distance = floatval($total_result['total_driving_distance'] ?? 0);

    // 4. 총 누적거리 = 최초 주행거리 + 모든 운행거리 합계
    $total_cumulative_distance = $initial_distance + $total_driving_distance;

    echo json_encode([
        'total_distance' => $total_cumulative_distance,
        'initial_distance' => $initial_distance,
        'monthly_distance' => $monthly_distance,
        'total_driving_distance' => $total_driving_distance
    ], JSON_UNESCAPED_UNICODE);
} catch (PDOException $Exception) {
    echo json_encode(['error' => $Exception->getMessage()]);
}
?>
