<?php
/**
 * Routes CRUD.
 *
 * @package DatvetaucaotocBooking
 */

declare(strict_types=1);

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class Datvetau_Booking_Route_Repository {

	public static function list_active(): array {
		global $wpdb;
		$table = Datvetau_Booking_Database::table( 'routes' );
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		return $wpdb->get_results(
			"SELECT * FROM {$table} WHERE is_active = 1 ORDER BY sort_order ASC, label ASC",
			ARRAY_A
		) ?: array();
	}

	public static function list_all(): array {
		global $wpdb;
		$table = Datvetau_Booking_Database::table( 'routes' );
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		return $wpdb->get_results( "SELECT * FROM {$table} ORDER BY sort_order ASC, label ASC", ARRAY_A ) ?: array();
	}

	public static function find_by_id( int $id ): ?array {
		global $wpdb;
		$table = Datvetau_Booking_Database::table( 'routes' );
		$row   = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE id = %d", $id ), ARRAY_A );
		return $row ?: null;
	}

	public static function find_by_slug( string $slug ): ?array {
		global $wpdb;
		$table = Datvetau_Booking_Database::table( 'routes' );
		$row   = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE slug = %s", $slug ), ARRAY_A );
		return $row ?: null;
	}

	public static function save( array $data, ?int $id = null ): int {
		global $wpdb;
		$table = Datvetau_Booking_Database::table( 'routes' );

		$row = array(
			'slug'             => sanitize_title( (string) ( $data['slug'] ?? '' ) ),
			'label'            => sanitize_text_field( (string) ( $data['label'] ?? '' ) ),
			'reverse_route_id' => ! empty( $data['reverse_route_id'] ) ? (int) $data['reverse_route_id'] : null,
			'sort_order'       => (int) ( $data['sort_order'] ?? 0 ),
			'is_active'        => ! empty( $data['is_active'] ) ? 1 : 0,
		);

		if ( $id ) {
			$wpdb->update( $table, $row, array( 'id' => $id ) );
			return $id;
		}

		$wpdb->insert( $table, $row );
		return (int) $wpdb->insert_id;
	}

	public static function delete( int $id ): void {
		global $wpdb;
		$table = Datvetau_Booking_Database::table( 'routes' );
		$wpdb->delete( $table, array( 'id' => $id ) );
	}
}
