<?php
require_once('includes/load.php');
page_require_level(3);

// Function to get all scanned AWB records for the current date
function get_scanned_awb() {
    global $db;
    $current_date = date('Y-m-d'); // Get current date in Y-m-d format
    $sql = "SELECT * FROM awb WHERE scan_status IS NOT NULL AND DATE(date_scan) = '{$current_date}'";
    return $db->query($sql);
}

// Function to get the latest scanned AWB record for the current date
function get_latest_scanned_awb() {
    global $db;
    $current_date = date('Y-m-d'); // Get current date in Y-m-d format
    $sql = "SELECT * FROM awb WHERE scan_status IS NOT NULL AND DATE(date_scan) = '{$current_date}' ORDER BY date_scan DESC LIMIT 1";
    return $db->query($sql)->fetch_assoc();
}

$scanned_awbs = get_scanned_awb();
$latest_awb = get_latest_scanned_awb();

$total_scan_in = $db->query("SELECT COUNT(DISTINCT resi) as total FROM awb WHERE DATE(date_scan) = '{$current_date}'")->fetch_assoc()['total'];
$total_scan_status = $db->query("SELECT COUNT(DISTINCT resi) as total FROM awb WHERE scan_status IS NOT NULL AND DATE(date_scan) = '{$current_date}'")->fetch_assoc()['total'];

$progress_percentage = ($total_scan_in > 0) ? ($total_scan_status / $total_scan_in) * 100 : 0;

$data = [
    'scanned_awbs' => [],
    'latest_awb' => $latest_awb,
    'progress_percentage' => round($progress_percentage, 2) // Tambahkan progress_percentage ke dalam data
];

while ($awb = $scanned_awbs->fetch_assoc()) {
    $data['scanned_awbs'][] = $awb;
}

header('Content-Type: application/json');
echo json_encode($data);
?>
