<?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
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    SELECT
        q.id,
        q.printer_id,
        q.status,
        q.file_name,
        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;
}

/*
|--------------------------------------------------------------------------
| PROTECT ACTIVE JOBS
|--------------------------------------------------------------------------
*/

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

    echo json_encode([

        'success' => false,

        'message' =>
            'Active print jobs cannot be deleted. Cancel a WAITING job first.'

    ]);

    exit;
}

/*
|--------------------------------------------------------------------------
| DELETE
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    DELETE FROM print_queue
    WHERE
        id = ?
        AND printer_id = ?
");

$stmt->execute([

    $jobId,

    $printerId

]);

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

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

    exit;
}

echo json_encode([

    'success' => true,

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

    'job_id' =>
        $jobId

], JSON_PRETTY_PRINT);