<?php
declare(strict_types=1);

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

require_login($conn);
process_post_only_or_redirect('../pages/member.php?view=profile');

$customerId = (int) (filter_input(INPUT_POST, 'customer_id', FILTER_VALIDATE_INT) ?: 0);
$carId = (int) (filter_input(INPUT_POST, 'car_id', FILTER_VALIDATE_INT) ?: 0);
$returnPath = process_safe_return_path((string) ($_POST['return_to'] ?? ''), '../pages/member.php?view=profile');

ensure_post_csrf_or_redirect('car_profile_photo_save', $returnPath);

if (!can_access($conn, 'member_edit')) {
    redirect_with_flash(
        $returnPath,
        'error',
        localized_flash_message('คุณไม่มีสิทธิ์แก้ไขรูปรถ', 'You do not have permission to edit vehicle photos.')
    );
}

if ($customerId <= 0 || $carId <= 0) {
    redirect_with_flash(
        $returnPath,
        'error',
        localized_flash_message('ไม่พบรถที่ต้องการอัปเดตรูป', 'Vehicle photo target was not found.')
    );
}

if (!customer_lookup_has_branch_access($conn, $customerId)) {
    redirect_with_flash(
        $returnPath,
        'error',
        localized_flash_message('คุณไม่มีสิทธิ์เข้าถึงข้อมูลลูกค้ารายนี้', 'You do not have access to this customer.')
    );
}

ensure_car_profile_columns($conn);

$carStmt = db_prepare($conn, "
    SELECT
        car.car_id,
        car.customer_id,
        car.plate_number,
        car.brand,
        car.model,
        car.profile_image_path,
        car.profile_image_name,
        cust.name AS customer_name
    FROM cars car
    INNER JOIN customers cust ON cust.customer_id = car.customer_id
    WHERE car.car_id = ?
        AND car.customer_id = ?
    LIMIT 1
");
$carStmt->bind_param('ii', $carId, $customerId);
$carStmt->execute();
$car = $carStmt->get_result()->fetch_assoc() ?: null;
$carStmt->close();

if (!$car) {
    redirect_with_flash(
        $returnPath,
        'error',
        localized_flash_message('ไม่พบรถที่ต้องการอัปเดตรูป', 'Vehicle photo target was not found.')
    );
}

$storedPhoto = null;
$oldProfilePath = (string) ($car['profile_image_path'] ?? '');

try {
    $storedPhoto = store_car_profile_upload(car_profile_uploaded_file_from_request('car_profile_photo'), 'car-profile-' . $carId);
    if (!$storedPhoto) {
        throw new RuntimeException(localized_text_value('กรุณาเลือกรูปรถก่อนบันทึก', 'Choose a vehicle photo before saving.'));
    }

    $conn->begin_transaction();

    $updateStmt = db_prepare($conn, "
        UPDATE cars
        SET profile_image_path = ?,
            profile_image_name = ?,
            profile_image_mime_type = ?,
            profile_image_uploaded_at = ?
        WHERE car_id = ?
            AND customer_id = ?
    ");
    $updateStmt->bind_param(
        'ssssii',
        $storedPhoto['file_path'],
        $storedPhoto['file_name'],
        $storedPhoto['mime_type'],
        $storedPhoto['uploaded_at'],
        $carId,
        $customerId
    );
    $updateStmt->execute();
    $updateStmt->close();

    audit_log($conn, array(
        'module_key' => 'car',
        'action_key' => 'update_photo',
        'entity_type' => 'car',
        'entity_id' => $carId,
        'customer_id' => $customerId,
        'car_id' => $carId,
        'message' => 'Vehicle profile photo updated.',
        'before' => array(
            'profile_image_path' => $oldProfilePath,
            'profile_image_name' => (string) ($car['profile_image_name'] ?? ''),
        ),
        'after' => array(
            'profile_image_path' => (string) ($storedPhoto['file_path'] ?? ''),
            'profile_image_name' => (string) ($storedPhoto['file_name'] ?? ''),
        ),
    ));

    $conn->commit();

    if ($oldProfilePath !== '' && $oldProfilePath !== (string) ($storedPhoto['file_path'] ?? '')) {
        delete_car_profile_file($oldProfilePath);
    }

    redirect_with_flash(
        $returnPath,
        'success',
        localized_flash_message('อัปเดตรูปโปรไฟล์รถเรียบร้อยแล้ว', 'Vehicle profile photo updated.')
    );
} catch (Throwable $exception) {
    try {
        $conn->rollback();
    } catch (Throwable $rollbackException) {
    }

    if (is_array($storedPhoto) && !empty($storedPhoto['absolute_path']) && is_file((string) $storedPhoto['absolute_path'])) {
        @unlink((string) $storedPhoto['absolute_path']);
    }

    log_process_failure('save_car_profile_photo', $exception, array(
        'customer_id' => $customerId,
        'car_id' => $carId,
        'plate_number' => (string) ($car['plate_number'] ?? ''),
    ));

    redirect_with_flash(
        $returnPath,
        'error',
        process_resolve_exception_message(
            $exception,
            localized_flash_message('บันทึกรูปรถไม่สำเร็จ', 'Vehicle photo could not be saved.'),
            true
        )
    );
}
