<?php
session_start();
require_once 'db.php';
header('Content-Type: application/json');

// This API can be accessed via session (for browser-triggered prints) 
// OR via direct parameters for background polling (on private local networks).
// For cloud deployments, passing an 'api_key' is highly recommended.

if (!isset($_GET['action']) || $_GET['action'] !== 'get_test') {
    if (!isset($_SESSION['user_id']) && !isset($_GET['api_key']) && !isset($_GET['user_id']) && !isset($_GET['user'])) {
        echo json_encode(['success' => false, 'message' => 'Unauthorized - Missing credentials']);
        exit;
    }
}

$user_id = (int)($_SESSION['user_id'] ?? $_GET['user_id'] ?? 0);

// If user_id is 0 but we have a 'user' (username) string, lookup the ID
if ($user_id === 0 && isset($_GET['user'])) {
    $uStmt = $pdo->prepare("SELECT id FROM users WHERE username = ? LIMIT 1");
    $uStmt->execute([$_GET['user']]);
    $user_id = (int)$uStmt->fetchColumn();
}
$action = $_GET['action'] ?? '';

if ($action === 'get_pending') {
    // Each terminal can have its own name
    $terminal = $_GET['terminal'] ?? 'Main Terminal';
    
    // Find oldest pending print for this user/terminal
    $stmt = $pdo->prepare("SELECT pq.id, pq.sale_id, s.total_amount, s.payment_method 
                           FROM print_queue pq
                           JOIN sales s ON pq.sale_id = s.id
                           WHERE pq.user_id = ? AND pq.status = 'Pending' 
                           ORDER BY pq.created_at ASC LIMIT 1");
    $stmt->execute([$user_id]);
    $job = $stmt->fetch();
    
    if ($job) {
        // Find the corresponding receipt file saved by sales.php
        $files = glob(__DIR__ . "/../receipts/Receipt_#{$job['sale_id']}_*.txt");
        if (!$files) {
             $files = glob(__DIR__ . "/../receipts/Receipt_#{$job['sale_id']}_*.pdf");
        }
        
        if ($files) {
            $latestFile = $files[0];
            $ext = pathinfo($latestFile, PATHINFO_EXTENSION);
            $content = file_get_contents($latestFile);
            
            echo json_encode([
                'success' => true,
                'job_id' => $job['id'],
                'sale_id' => $job['sale_id'],
                'extension' => $ext,
                'content' => base64_encode($content), // Encode for binary safety
                'filename' => basename($latestFile)
            ]);
        } else {
            // Still no file? Maybe it's being generated.
            echo json_encode(['success' => false, 'message' => 'File not found on server']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'No pending jobs']);
    }
} elseif ($action === 'mark_printed') {
    $job_id = (int)($_GET['id'] ?? 0);
    
    // 1. Find job and file path
    $stmt = $pdo->prepare("SELECT file_path FROM print_queue WHERE id = ?");
    $stmt->execute([$job_id]);
    $file_path = $stmt->fetchColumn();

    // 2. Update status
    $stmt = $pdo->prepare("UPDATE print_queue SET status = 'Printed' WHERE id = ? AND user_id = ?");
    if ($stmt->execute([$job_id, $user_id])) {
        
        // 3. Move file to archived if it exists
        if ($file_path) {
            $source = __DIR__ . "/../receipts/" . $file_path;
            $archDir = __DIR__ . "/../receipts/archived/";
            if (!is_dir($archDir)) {
                mkdir($archDir, 0777, true);
            }
            if (file_exists($source)) {
                rename($source, $archDir . $file_path);
            }
        }
        
        echo json_encode(['success' => true, 'message' => 'Job marked as printed and archived']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to update status']);
    }
} elseif ($action === 'enqueue') {
    // Only internal or authenticated users can enqueue
    if (!isset($_SESSION['user_id'])) exit;
    
    $sale_id = $_GET['sale_id'] ?? 0;
    $terminal = $_GET['terminal'] ?? 'Main Terminal';
    
    $stmt = $pdo->prepare("INSERT INTO print_queue (sale_id, user_id, terminal_name) VALUES (?, ?, ?)");
    if ($stmt->execute([$sale_id, $_SESSION['user_id'], $terminal])) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false]);
    }
} elseif ($action === 'get_test') {
    header('Content-Type: text/plain');
    echo "\n\n";
    echo "   JUSTSALE POS TEST   \n";
    echo "-----------------------\n";
    echo "Status: SUCCESSFUL\n";
    echo "Date: " . date('Y-m-d H:i') . "\n";
    echo "-----------------------\n";
    echo "If you can see this, your\n";
    echo "printer is correctly   \n";
    echo "connected via Bluetooth.\n";
    echo "\n\n\n\n\n";
    echo "\x1d\x56\x42\x00"; // GS V 66 0 (Standard Paper Cut)
    exit;
}
?>
