<?php
require_once('includes/load.php'); // Load necessary files
session_start(); // Start the session

// Check if ID is provided
if (isset($_POST['id'])) {
    $id = (int)$_POST['id'];

    // Update print count in resi_uploads (Jakarta)
    $stmt = $db->prepare("UPDATE resi_uploads SET print_times = print_times + 1 WHERE id = ?");
    if ($stmt) {
        $stmt->bind_param('i', $id);
        if ($stmt->execute()) {
            $stmt->close(); // Close the previous statement

            // Fetch updated print count from resi_uploads (Jakarta)
            $stmt = $db->prepare("SELECT print_times FROM resi_uploads WHERE id = ?");
            if ($stmt) {
                $stmt->bind_param('i', $id);
                $stmt->execute();
                $stmt->bind_result($print_times_jakarta);
                $stmt->fetch();
                $stmt->close(); // Close the statement
            } else {
                echo 'Error preparing statement to fetch Jakarta print count.';
                exit;
            }
        } else {
            echo 'Error updating print count for Jakarta.';
            exit;
        }
    } else {
        echo 'Error preparing Jakarta update statement.';
        exit;
    }

    // Update print count in resi_uploads_surabaya (Surabaya)
    $stmt = $db->prepare("UPDATE resi_uploads_surabaya SET print_times = print_times + 1 WHERE id = ?");
    if ($stmt) {
        $stmt->bind_param('i', $id);
        if ($stmt->execute()) {
            $stmt->close(); // Close the previous statement

            // Fetch updated print count from resi_uploads_surabaya (Surabaya)
            $stmt = $db->prepare("SELECT print_times FROM resi_uploads_surabaya WHERE id = ?");
            if ($stmt) {
                $stmt->bind_param('i', $id);
                $stmt->execute();
                $stmt->bind_result($print_times_surabaya);
                $stmt->fetch();
                $stmt->close(); // Close the statement
            } else {
                echo 'Error preparing statement to fetch Surabaya print count.';
                exit;
            }
        } else {
            echo 'Error updating print count for Surabaya.';
            exit;
        }
    } else {
        echo 'Error preparing Surabaya update statement.';
        exit;
    }

    // Cek apakah print_times null dan set ke 0 jika perlu
    $print_times_jakarta = $print_times_jakarta ?? 0;
    $print_times_surabaya = $print_times_surabaya ?? 0;

    // Return both Jakarta and Surabaya print counts
    $response = array(
        'print_times_jakarta' => $print_times_jakarta,
        'print_times_surabaya' => $print_times_surabaya
    );
    echo json_encode($response); // Return the new print counts as JSON

} else {
    echo 'Invalid request.';
}
?>
