<?php
include 'auth.php'; // Handles session, db, and permissions loading
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Check permissions first
if (empty($_POST['id'])) {
require_permission('cars_add');
} else {
require_permission('cars_edit');
}
// --- Get main car data ---
$id = !empty($_POST['id']) ? (int)$_POST['id'] : null;
$name = $_POST['name'];
$brand = $_POST['brand'];
$model = $_POST['model'];
$year = $_POST['year'];
$category = $_POST['category'];
$description = $_POST['description'];
$video_url = $_POST['video_url'] ?? '';
// Start transaction to ensure atomic saving of car + trims
$conn->begin_transaction();
try {
// --- Database Operation for Cars (Main) ---
if (empty($id)) {
// This is an INSERT operation
$sql = "INSERT INTO cars (name, brand, model, year, category, description, video_url) VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssisss", $name, $brand, $model, $year, $category, $description, $video_url);
} else {
// This is an UPDATE operation
$sql = "UPDATE cars SET name=?, brand=?, model=?, year=?, category=?, description=?, video_url=? WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssisssi", $name, $brand, $model, $year, $category, $description, $video_url, $id);
}
if (!$stmt->execute()) {
throw new Exception("Error saving car: " . $stmt->error);
}
$car_id = empty($id) ? $conn->insert_id : $id;
$stmt->close();
// --- Handle Car Trims ---
$posted_trim_ids = [];
$pdf_dir = '../uploads/pdfs/';
if (!is_dir($pdf_dir)) {
mkdir($pdf_dir, 0777, true);
}
if (isset($_POST['trims']) && is_array($_POST['trims'])) {
foreach ($_POST['trims'] as $index => $trim_data) {
$trim_id = !empty($trim_data['id']) ? (int)$trim_data['id'] : null;
$trim_name = $trim_data['name'];
$trim_price = $trim_data['price'];
$fuel_type = $trim_data['fuel_type'];
$car_condition = $trim_data['car_condition'];
$engine_capacity = $trim_data['engine_capacity'] ?? '';
$transmission_type = $trim_data['transmission_type'] ?? '';
$horsepower = !empty($trim_data['horsepower']) ? (int)$trim_data['horsepower'] : 0;
$torque = $trim_data['torque'] ?? '';
$acceleration = $trim_data['acceleration'] ?? '';
$top_speed = $trim_data['top_speed'] ?? '';
$fuel_consumption = $trim_data['fuel_consumption'] ?? '';
$drivetrain = $trim_data['drivetrain'] ?? '';
$seating_capacity = !empty($trim_data['seating_capacity']) ? (int)$trim_data['seating_capacity'] : 0;
$body_type = $trim_data['body_type'] ?? '';
$exterior_color = $trim_data['exterior_color'] ?? '';
$interior_color = $trim_data['interior_color'] ?? '';
// Handle Trim PDF
$existing_pdf = $trim_data['tech_specs_pdf_existing'] ?? '';
$pdf_name = $existing_pdf;
// Check for remove PDF request
if (isset($trim_data['remove_pdf']) && $trim_data['remove_pdf'] == '1' && !empty($existing_pdf)) {
if (file_exists($pdf_dir . $existing_pdf)) {
unlink($pdf_dir . $existing_pdf);
}
$pdf_name = null;
}
// Check for new PDF file upload
$file_input_name = 'tech_specs_pdf_' . $index;
if (isset($_FILES[$file_input_name]) && $_FILES[$file_input_name]['error'] == 0) {
// Delete old PDF if exists
if (!empty($existing_pdf) && file_exists($pdf_dir . $existing_pdf)) {
unlink($pdf_dir . $existing_pdf);
}
// Generate unique file name
$pdf_name = uniqid() . '-' . basename($_FILES[$file_input_name]['name']);
if (!move_uploaded_file($_FILES[$file_input_name]['tmp_name'], $pdf_dir . $pdf_name)) {
throw new Exception("Failed to upload PDF for trim: " . $trim_name);
}
}
if (empty($trim_id)) {
// Insert new trim
$trim_sql = "INSERT INTO car_trims (
car_id, name, price, fuel_type, car_condition,
engine_capacity, transmission_type, horsepower, torque,
acceleration, top_speed, fuel_consumption, drivetrain,
seating_capacity, body_type, exterior_color, interior_color, tech_specs_pdf
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$trim_stmt = $conn->prepare($trim_sql);
$trim_stmt->bind_param("isdsssssssssisssss",
$car_id, $trim_name, $trim_price, $fuel_type, $car_condition,
$engine_capacity, $transmission_type, $horsepower, $torque,
$acceleration, $top_speed, $fuel_consumption, $drivetrain,
$seating_capacity, $body_type, $exterior_color, $interior_color, $pdf_name
);
} else {
// Update existing trim
$trim_sql = "UPDATE car_trims SET
name=?, price=?, fuel_type=?, car_condition=?,
engine_capacity=?, transmission_type=?, horsepower=?, torque=?,
acceleration=?, top_speed=?, fuel_consumption=?, drivetrain=?,
seating_capacity=?, body_type=?, exterior_color=?, interior_color=?, tech_specs_pdf=?
WHERE id=? AND car_id=?";
$trim_stmt = $conn->prepare($trim_sql);
$trim_stmt->bind_param("sdsssssssssisssssii",
$trim_name, $trim_price, $fuel_type, $car_condition,
$engine_capacity, $transmission_type, $horsepower, $torque,
$acceleration, $top_speed, $fuel_consumption, $drivetrain,
$seating_capacity, $body_type, $exterior_color, $interior_color, $pdf_name,
$trim_id, $car_id
);
$posted_trim_ids[] = $trim_id;
}
if (!$trim_stmt->execute()) {
throw new Exception("Error saving trim: " . $trim_stmt->error);
}
if (empty($trim_id)) {
$posted_trim_ids[] = $trim_stmt->insert_id;
}
$trim_stmt->close();
}
}
// --- Delete removed trims from DB ---
if (!empty($id)) {
// Fetch all current trims in database
$db_trims_query = $conn->prepare("SELECT id, tech_specs_pdf FROM car_trims WHERE car_id = ?");
$db_trims_query->bind_param("i", $id);
$db_trims_query->execute();
$db_trims_res = $db_trims_query->get_result();
while ($db_trim = $db_trims_res->fetch_assoc()) {
if (!in_array($db_trim['id'], $posted_trim_ids)) {
// This trim was deleted from UI, remove its PDF first if exists
if (!empty($db_trim['tech_specs_pdf']) && file_exists($pdf_dir . $db_trim['tech_specs_pdf'])) {
unlink($pdf_dir . $db_trim['tech_specs_pdf']);
}
// Delete the record
$delete_stmt = $conn->prepare("DELETE FROM car_trims WHERE id = ?");
$delete_stmt->bind_param("i", $db_trim['id']);
$delete_stmt->execute();
$delete_stmt->close();
}
}
$db_trims_query->close();
}
// --- Handle Multiple Images Upload ---
if (isset($_FILES['car_images']) && !empty($_FILES['car_images']['name'][0])) {
$upload_dir = '../uploads/cars/';
$existing_images_count = 0;
$count_stmt = $conn->prepare("SELECT COUNT(*) as count FROM car_images WHERE car_id = ?");
$count_stmt->bind_param("i", $car_id);
$count_stmt->execute();
$count_result = $count_stmt->get_result();
$existing_images_count = $count_result->fetch_assoc()['count'];
$count_stmt->close();
for ($i = 0; $i < count($_FILES['car_images']['name']); $i++) {
if ($_FILES['car_images']['error'][$i] == 0) {
$unique_filename = uniqid() . '-' . basename($_FILES['car_images']['name'][$i]);
$target_file = $upload_dir . $unique_filename;
if (move_uploaded_file($_FILES['car_images']['tmp_name'][$i], $target_file)) {
$is_primary = ($existing_images_count == 0 && $i == 0) ? 1 : 0;
$sort_order = $existing_images_count + $i + 1;
$img_stmt = $conn->prepare("INSERT INTO car_images (car_id, image_name, is_primary, sort_order) VALUES (?, ?, ?, ?)");
$img_stmt->bind_param("isii", $car_id, $unique_filename, $is_primary, $sort_order);
$img_stmt->execute();
$img_stmt->close();
}
}
}
}
// Commit transaction
$conn->commit();
header("Location: cars.php?success=تم حفظ السيارة والفئات بنجاح");
} catch (Exception $e) {
// Rollback transaction on error
$conn->rollback();
header("Location: cars.php?error=حدث خطأ أثناء حفظ البيانات: " . $e->getMessage());
}
$conn->close();
} else {
header("Location: cars.php");
exit();
}
?>