<?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);

$jobId = (int)($data['job_id'] ?? 0);

if ($printerId <= 0 || $jobId <= 0) {

    echo json_encode([
        'success' => false,
        'message' => 'Printer ID and Job ID are required.'
    ]);

    exit;
}

/*
|--------------------------------------------------------------------------
| VERIFY JOB BELONGS TO AGENT'S PRINTER
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    SELECT
        q.id,
        q.printer_id,
        q.file_name,
        q.status,
        q.order_id
    FROM print_queue q

    INNER JOIN agent_printers ap
        ON ap.printer_id = q.printer_id

    WHERE
        q.id = ?
        AND q.printer_id = ?
        AND ap.agent_id = ?

    LIMIT 1
");

$stmt->execute([

    $jobId,

    $printerId,

    $agentId

]);

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

if (!$job) {

    echo json_encode([
        'success' => false,
        'message' => 'Job not found.'
    ]);

    exit;
}

/*
|--------------------------------------------------------------------------
| ONLY WAITING JOB CAN BE CANCELLED
|--------------------------------------------------------------------------
*/

if ($job['status'] !== 'WAITING') {

    echo json_encode([

        'success' => false,

        'message' =>
            'Only WAITING jobs can be cancelled. PRINTING jobs cannot be interrupted safely.'

    ]);

    exit;
}

/*
|--------------------------------------------------------------------------
| CANCEL JOB
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    UPDATE print_queue
    SET
        status = 'FAILED',
        completed_at = CURRENT_TIMESTAMP,
        error_message = ?
    WHERE
        id = ?
        AND printer_id = ?
        AND status = 'WAITING'
");

$stmt->execute([

    'Cancelled by printer owner.',

    $jobId,

    $printerId

]);

if ($stmt->rowCount() !== 1) {

    echo json_encode([
        'success' => false,
        'message' => 'Job could not be cancelled. It may already be printing.'
    ]);

    exit;
}

echo json_encode([

    'success' => true,

    'message' =>
        'Print job cancelled successfully.',

    'job' => [

        'id' =>
            $jobId,

        'printer_id' =>
            $printerId,

        'order_id' =>
            (int)$job['order_id'],

        'file_name' =>
            $job['file_name'],

        'status' =>
            'FAILED'

    ]

], JSON_PRETTY_PRINT);