<?php

require_once __DIR__ . '/../../core/bootstrap.php';

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

$user = authenticate($pdo);

if (!in_array($user['role'], ['sp_admin', 'artisan'], true)) {
    json_response(false, 'Access denied. SP role required.', [], 403);
}

$sp_company_id = (int)$user['company_id'];
$rsp_id        = (int)$user['rsp_id'];

/* ----------------------------------------------------------
   Input Validation
---------------------------------------------------------- */

if (empty($_POST['breakdown_id']) || !isset($_FILES['photo'])) {
    json_response(false, 'Breakdown ID and photo required.', [], 400);
}

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

if ($breakdown_id <= 0) {
    json_response(false, 'Invalid breakdown ID.', [], 400);
}

$pdo->beginTransaction();

try {

    /*
    |--------------------------------------------------------------------------
    | Fetch Breakdown + RSP Scope
    |--------------------------------------------------------------------------
    */

    $stmt = $pdo->prepare("
        SELECT b.id, b.status, b.archived_at,
               b.accepted_company_id,
               f.rsp_id
        FROM breakdowns b
        JOIN companies f ON f.id = b.fleet_company_id
        WHERE b.id = ?
        LIMIT 1
    ");

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

    if (!$breakdown) {
        $pdo->rollBack();
        json_response(false, 'Breakdown not found.', [], 404);
    }

    /* RSP Isolation */
    if ((int)$breakdown['rsp_id'] !== $rsp_id) {
        $pdo->rollBack();
        json_response(false, 'Access denied.', [], 403);
    }

    /* Must belong to this SP */
    if ((int)$breakdown['accepted_company_id'] !== $sp_company_id) {
        $pdo->rollBack();
        json_response(false, 'Not assigned to your company.', [], 403);
    }

    /* Archive Lock */
    if (!empty($breakdown['archived_at'])) {
        $pdo->rollBack();
        json_response(false, 'Archived jobs cannot be modified.', [], 403);
    }

    /*
    |--------------------------------------------------------------------------
    | File Validation
    |--------------------------------------------------------------------------
    */

    $file = $_FILES['photo'];

    if ($file['error'] !== UPLOAD_ERR_OK) {
        $pdo->rollBack();
        json_response(false, 'File upload error.', [], 400);
    }

    /* Max 10MB */
    if ($file['size'] > 10 * 1024 * 1024) {
        $pdo->rollBack();
        json_response(false, 'File too large. Max 10MB.', [], 413);
    }

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = $finfo->file($file['tmp_name']);

    $allowed_types = [
        'image/jpeg' => 'jpg',
        'image/png'  => 'png',
        'image/webp' => 'webp'
    ];

    if (!isset($allowed_types[$mime])) {
        $pdo->rollBack();
        json_response(false, 'Invalid file type.', [], 400);
    }

    $extension = $allowed_types[$mime];

    /*
    |--------------------------------------------------------------------------
    | Safe Storage Path
    |--------------------------------------------------------------------------
    */

    $upload_dir = __DIR__ . '/../../uploads/breakdowns/' . $breakdown_id;

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

    /* Unique filename */
    $filename = bin2hex(random_bytes(16)) . '.' . $extension;
    $destination = $upload_dir . '/' . $filename;

    if (!move_uploaded_file($file['tmp_name'], $destination)) {
        $pdo->rollBack();
        json_response(false, 'Failed to store file.', [], 500);
    }

    /*
    |--------------------------------------------------------------------------
    | Store DB Record
    |--------------------------------------------------------------------------
    */

    $relative_path = "uploads/breakdowns/{$breakdown_id}/{$filename}";

    $stmt = $pdo->prepare("
        INSERT INTO breakdown_photos (breakdown_id, file_path, created_at)
        VALUES (?, ?, NOW())
    ");

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

    $pdo->commit();

    json_response(true, 'Photo uploaded successfully.', [
        'file_path' => $relative_path
    ]);

} catch (Throwable $e) {

    $pdo->rollBack();
    json_response(false, 'Photo upload failed.', [], 500);
}