<?php

require_once __DIR__ . '/../../core/api_bootstrap.php';
require_once __DIR__ . '/../../core/permissions.php';

/* METHOD */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(false, 'Invalid request method.', [], 405);
}

/* AUTH */
$user = authenticate($pdo);

/* RBAC */
require_permission($user, 'breakdowns', 'edit', $pdo);

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

if (!is_array($input) || empty($input['breakdown_id'])) {
    json_response(false, 'Breakdown ID required.', [], 400);
}

$breakdown_id = (int)$input['breakdown_id'];

$pdo->beginTransaction();

try {

    /*
    |------------------------------------------------------------------
    | LOCK BREAKDOWN ROW
    |------------------------------------------------------------------
    */

    $stmt = $pdo->prepare("
        SELECT b.*, f.rsp_id
        FROM breakdowns b
        JOIN companies f ON f.id = b.fleet_company_id
        WHERE b.id = ?
        FOR UPDATE
    ");

    $stmt->execute([$breakdown_id]);
    $breakdown = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$breakdown) {
        throw new Exception('Breakdown not found.');
    }

    /*
    |------------------------------------------------------------------
    | TENANT ISOLATION
    |------------------------------------------------------------------
    */

    if (!empty($user['rsp_id']) && (int)$breakdown['rsp_id'] !== (int)$user['rsp_id']) {
        throw new Exception('Access denied.');
    }

    /*
    |------------------------------------------------------------------
    | STATE VALIDATION
    |------------------------------------------------------------------
    */

    if ($breakdown['status'] !== 'completed') {
        throw new Exception('Only completed jobs can be archived.');
    }

    if (!empty($breakdown['archived_at'])) {
        throw new Exception('Already archived.');
    }

    /*
    |------------------------------------------------------------------
    | FETCH PHOTOS
    |------------------------------------------------------------------
    */

    $stmt = $pdo->prepare("
        SELECT file_path
        FROM breakdown_photos
        WHERE breakdown_id = ?
        ORDER BY id ASC
    ");

    $stmt->execute([$breakdown_id]);
    $photos = $stmt->fetchAll(PDO::FETCH_COLUMN);

    /*
    |------------------------------------------------------------------
    | SNAPSHOT BUILD
    |------------------------------------------------------------------
    */

    $snapshot = [
        'breakdown'   => $breakdown,
        'photos'      => $photos,
        'archived_at' => date('Y-m-d H:i:s')
    ];

    $snapshot_json = json_encode($snapshot, JSON_UNESCAPED_UNICODE);
    $archive_hash  = hash('sha256', $snapshot_json);

    /*
    |------------------------------------------------------------------
    | FILE STORAGE
    |------------------------------------------------------------------
    */

    $snapshot_dir = __DIR__ . '/../../storage/archives';

    if (!is_dir($snapshot_dir)) {
        mkdir($snapshot_dir, 0755, true);
    }

    $snapshot_file = $snapshot_dir . "/archive_{$breakdown_id}.json";

    if (!file_put_contents($snapshot_file, $snapshot_json)) {
        throw new Exception('Failed to store archive snapshot.');
    }

    /*
    |------------------------------------------------------------------
    | UPDATE BREAKDOWN
    |------------------------------------------------------------------
    */

    $stmt = $pdo->prepare("
        UPDATE breakdowns
        SET status = 'archived',
            archived_at = NOW(),
            archive_hash = ?
        WHERE id = ?
    ");

    $stmt->execute([$archive_hash, $breakdown_id]);

    $pdo->commit();

    json_response(true, 'Breakdown archived successfully.', [
        'archive_hash' => $archive_hash
    ]);

} catch (Throwable $e) {

    $pdo->rollBack();
    json_response(false, $e->getMessage(), [], 400);
}