File Manager V1.5

[SYSTEM@ROOT]: /var/www/html/
INJECT_FILE:
NEW_ENTRY:

FILE_CONTENT: create_booking.php

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH, OPTIONS");
header("Access-Control-Allow-Headers: Authorization, Content-Type, Accept, X-Requested-With, User-Agent, Origin");
header("Access-Control-Max-Age: 86400");
header("Content-Type: application/json; charset=UTF-8");

define('CAR_STATUS_BOOKED', 'booked');
define('CAR_STATUS_FOR_NEW_TB', 'pending');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

require __DIR__ . '/vendor/autoload.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

require_once 'db.php';

function sendResponse($success, $message = '', $data = null, $code = 200) {
    http_response_code($code);
    echo json_encode([
        'success' => $success,
        'message' => $message,
        'data' => $data,
        'timestamp' => time()
    ]);
    exit;
}

try {
    $headers = getallheaders();
    if (!isset($headers['Authorization'])) {
        sendResponse(false, 'Требуется авторизация', null, 401);
    }

    $token = str_replace('Bearer ', '', $headers['Authorization']);
    $decoded = verifyToken($token); 
    if (!$decoded) {
        sendResponse(false, 'Неверный токен', null, 401);
    }

    $input = json_decode(file_get_contents('php://input'), true);
    if (!isset($input['car_id']) || !isset($input['booking_date']) || !isset($input['booking_end'])) {
        sendResponse(false, 'Отсутствуют обязательные поля', null, 400);
    }

    $carId = $input['car_id'];
    $bookingDate = $input['booking_date'];
    $bookingEnd = $input['booking_end'];
    $userId = $decoded['user_id'];

    $pdo = getPDO();
    if (!$pdo) {
        sendResponse(false, 'Ошибка подключения к БД', null, 500);
    }

    $ownerCheckStmt = $pdo->prepare("SELECT user_id FROM car_listings WHERE id = ?");
    $ownerCheckStmt->execute([$carId]);
    $owner = $ownerCheckStmt->fetch(PDO::FETCH_ASSOC);

    if (!$owner) {
        sendResponse(false, 'Автомобиль не найден', null, 404);
    }

    if ($owner['user_id'] == $userId) {
        sendResponse(false, 'Нельзя бронировать свой автомобиль', null, 403);
    }

    $stmt = $pdo->prepare("
        SELECT COUNT(*) FROM bookings 
        WHERE car_id = ? AND (
            (booking_date <= ? AND booking_end >= ?) OR
            (booking_date <= ? AND booking_end >= ?) OR
            (booking_date >= ? AND booking_end <= ?)
        )
    ");
    $stmt->execute([$carId, $bookingEnd, $bookingDate, $bookingDate, $bookingEnd, $bookingDate, $bookingEnd]);

    if ($stmt->fetchColumn() > 0) {
        sendResponse(false, 'Машина уже забронирована на этот период', null, 400);
    }

    $insertStmt = $pdo->prepare("
        INSERT INTO bookings (car_id, user_id, booking_date, booking_end, status)
        VALUES (?, ?, ?, ?, ?)
    ");
    $insertStmt->execute([$carId, $userId, $bookingDate, $bookingEnd, CAR_STATUS_FOR_NEW_TB]);
    $bookingId = $pdo->lastInsertId();

    $updateCarStatusStmt = $pdo->prepare("UPDATE car_listings SET status = ? WHERE id = ?");
    $updateCarStatusStmt->execute([CAR_STATUS_BOOKED, $carId]);

    sendResponse(true, 'Бронирование успешно создано', [
        'id' => $bookingId,
        'car_id' => $carId,
        'user_id' => $userId,
        'booking_date' => $bookingDate,
        'booking_end' => $bookingEnd,
        'status' => CAR_STATUS_BOOKED
    ], 201);

} catch (PDOException $e) {
    sendResponse(false, 'Ошибка базы данных: ' . $e->getMessage(), null, 500);
} catch (Exception $e) {
    sendResponse(false, 'Ошибка сервера: ' . $e->getMessage(), null, 500);
}
?>
[ KEMBALI ]