<?php

declare(strict_types=1);

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

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/auth_check.php';

$db = new Database();
$pdo = $db->connect();

$data = json_decode(file_get_contents('php://input'), true);

if (!is_array($data)) {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid JSON request.'
    ]);
    exit;
}

$auth = authenticateAgent($pdo, $data);

if (!$auth['success']) {
    echo json_encode($auth);
    exit;
}

$agent = $auth['agent'];

$agentId = (int)$agent['id'];

$printerId = (int)($data['printer_id'] ?? 0);

if ($printerId <= 0) {
    echo json_encode([
        'success' => false,
        'message' => 'Printer ID is required.'
    ]);
    exit;
}

/*
|--------------------------------------------------------------------------
| VERIFY PRINTER
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    SELECT
        p.id,
        p.printer_name,
        p.printer_code,
        ap.windows_printer,
        ap.computer_name,
        ap.printer_model,
        ap.printer_port,
        ap.printer_driver,
        ap.status AS agent_printer_status,
        ap.printer_status
    FROM printers p

    INNER JOIN agent_printers ap
        ON ap.printer_id = p.id

    WHERE
        p.id = ?
        AND ap.agent_id = ?

    LIMIT 1
");

$stmt->execute([
    $printerId,
    $agentId
]);

$printer = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$printer) {
    echo json_encode([
        'success' => false,
        'message' => 'Printer not found.'
    ]);
    exit;
}

/*
|--------------------------------------------------------------------------
| GET QUEUE
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    SELECT
        id,
        order_id,
        printer_id,
        file_name,
        pdf_path,
        copies,
        status,
        created_at,
        started_at,
        completed_at,
        error_message
    FROM print_queue
    WHERE printer_id = ?
    ORDER BY id ASC
");

$stmt->execute([$printerId]);

$jobs = $stmt->fetchAll(PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| SUMMARY
|--------------------------------------------------------------------------
*/

$summary = [
    'total'     => 0,
    'waiting'   => 0,
    'printing'  => 0,
    'completed' => 0,
    'failed'    => 0
];

foreach ($jobs as $job) {

    $summary['total']++;

    $status = strtolower((string)$job['status']);

    if (isset($summary[$status])) {
        $summary[$status]++;
    }
}

/*
|--------------------------------------------------------------------------
| FIND NEXT WAITING JOB
|--------------------------------------------------------------------------
*/

$nextJob = null;

foreach ($jobs as $job) {

    if (strtoupper((string)$job['status']) === 'WAITING') {
        $nextJob = $job;
        break;
    }
}

/*
|--------------------------------------------------------------------------
| RESPONSE
|--------------------------------------------------------------------------
*/

echo json_encode([
    'success' => true,

    'printer' => [
        'id' => (int)$printer['id'],
        'printer_name' => $printer['printer_name'],
        'printer_code' => $printer['printer_code'],
        'windows_printer' => $printer['windows_printer'],
        'computer_name' => $printer['computer_name'],
        'printer_model' => $printer['printer_model'],
        'printer_port' => $printer['printer_port'],
        'printer_driver' => $printer['printer_driver'],
        'agent_printer_status' => $printer['agent_printer_status'],
        'printer_status' => $printer['printer_status']
    ],

    'summary' => $summary,

    'next_job' => $nextJob,

    'jobs' => $jobs

], JSON_PRETTY_PRINT);