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

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

$num = isset($_GET['num']) ? $_GET['num'] : '';

$response = ['success' => false];

if ($num) {
    try {
        $pdo = db_connect();

        $sql = "SELECT slatlist FROM chandj.output WHERE num = ?";
        $stmh = $pdo->prepare($sql);
        $stmh->bindValue(1, $num, PDO::PARAM_INT);
        $stmh->execute();

        $row = $stmh->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            $slatlist = json_decode($row['slatlist'], true);
            if (is_array($slatlist)) {
                $totalCompleted = 0;
                $totalItems = 0;
                foreach ($slatlist as $item) {
                    $totalItems += isset($item['number']) ? (float)$item['number'] : 0;
                    if (isset($item['done_check']) && $item['done_check'] == "1") {
                        $totalCompleted += isset($item['number']) ? (float)$item['number'] : 0;
                    }
                }
                $response['success'] = true;
                $response['totalCompleted'] = $totalCompleted;
                $response['totalItems'] = $totalItems;
            } else {
                $response['message'] = "Invalid slatlist format";
            }
        } else {
            $response['message'] = "No data found";
        }
    } catch (PDOException $e) {
        $response['message'] = "Error: " . $e->getMessage();
    }
}

echo json_encode($response);
?>
