<?php
// update_cloud_printing.php
require_once 'api/db.php';

try {
    echo "<h2>Cloud Printing Database Sync</h2>";

    // 1. Create or Update Print Queue Table
    $pdo->exec("CREATE TABLE IF NOT EXISTS `print_queue` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `sale_id` int(11) NOT NULL,
        `user_id` int(11) NOT NULL,
        `file_path` varchar(255) DEFAULT NULL,
        `terminal_name` varchar(50) DEFAULT 'Main Terminal',
        `status` enum('Pending','Printed') DEFAULT 'Pending',
        `created_at` timestamp DEFAULT current_timestamp(),
        PRIMARY KEY (`id`),
        INDEX (`user_id`),
        INDEX (`status`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    // 2. Ensure file_path column exists
    $cols = $pdo->query("SHOW COLUMNS FROM `print_queue` LIKE 'file_path'")->fetch();
    if (!$cols) {
        $pdo->exec("ALTER TABLE `print_queue` ADD COLUMN `file_path` varchar(255) AFTER `user_id`;");
        echo "Added 'file_path' column.<br>";
    }

    echo "<hr>";
    if (isset($_GET['action']) && $_GET['action'] === 'clear') {
        $pdo->exec("TRUNCATE TABLE `print_queue`;");
        echo "<h3 style='color:orange'>Print Queue Cleared.</h3>";
        echo "<p>All old stuck jobs are gone. You can now try a fresh sale.</p>";
    } else {
        echo "<h3 style='color:green'>Migration Complete!</h3>";
        echo "<p>To clear old stuck jobs, <a href='?action=clear'>click here</a>.</p>";
        echo "<p>Otherwise, return to the POS and try a new sale.</p>";
    }

} catch (Exception $e) {
    echo "<hr>";
    echo "<h3 style='color:red'>Migration Failed!</h3>";
    echo "<p>Error: " . $e->getMessage() . "</p>";
}
?>
