diff --git a/TODO.md b/TODO.md index e9238bc..62013ea 100644 --- a/TODO.md +++ b/TODO.md @@ -25,8 +25,8 @@ ## What has to be done - [x] Vehicle delete - [ ] intro tutorial when no car exist or just dont show anything -- [ ] change/set default car -- [ ] hide errors +- [x] change/set default car +- [x] hide errors ## Nice to have - [ ] specific car view - charts, fuel records diff --git a/app/controllers/VehicleController.php b/app/controllers/VehicleController.php index 231e8dc..f5f7ede 100644 --- a/app/controllers/VehicleController.php +++ b/app/controllers/VehicleController.php @@ -75,6 +75,18 @@ class VehicleController extends Controller { $this->view('vehicles/index', ['title' => 'Vehicles', 'vehicles' => $vehicles]); } + public function setDefault() { + $vehicle = new Vehicle(); + // TODO: Validate the request + $result = $vehicle->setDefaultVehicle($_POST['vehicle_id'], $_SESSION['user']['id']); + if($result != true) { + echo "Something went wrong"; + return; + } + + $this->view('vehicles/index', ['title' => 'Vehicles', 'vehicles' => $vehicles]); + } + public function api_get() { if(!$_SERVER['REQUEST_METHOD'] === 'GET') { echo "Wrong method, use GET"; diff --git a/app/models/Vehicle.php b/app/models/Vehicle.php index 6884c9f..c22349b 100644 --- a/app/models/Vehicle.php +++ b/app/models/Vehicle.php @@ -61,6 +61,39 @@ class Vehicle { return $result->fetch_assoc(); } + public function setDefaultVehicle($vehicle_id, $user_id) { + try { + $this->db->begin_transaction(); + + $stmt = $this->db->prepare(" + UPDATE `vehicles` + SET `is_default` = 0 + WHERE `user_id` = ? AND `is_default` = 1 + "); + $stmt->bind_param("i", $user_id); + $stmt->execute(); + $stmt->close(); + + $stmt = $this->db->prepare(" + UPDATE `vehicles` + SET `is_default` = 1 + WHERE `id` = ? AND `user_id` = ? + "); + $stmt->bind_param("ii", $vehicle_id, $user_id); + + if ($stmt->execute()) { + $this->db->commit(); + return true; + } else { + $this->db->rollback(); + return "Error: " . $stmt->error; + } + } catch (mysqli_sql_exception $e) { + $this->db->rollback(); + return $e->getMessage(); + } + } + public function delete($vehicle_id, $user_id) { try { $stmt = $this->db->prepare("SELECT id FROM vehicles WHERE id = ? AND user_id = ?"); diff --git a/app/views/vehicles/index.php b/app/views/vehicles/index.php index 7d86f3a..3d04b15 100644 --- a/app/views/vehicles/index.php +++ b/app/views/vehicles/index.php @@ -14,10 +14,15 @@
= htmlspecialchars($vehicle['fuel_type']) ?>
= htmlspecialchars($vehicle['note'] ?? "") ?>