<?php
/**
 * Branch repository.
 *
 * @package Lucrativeit_Subscription_Recurring_Billing
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Data access for branches.
 */
class LUCRSURE_Branch_Repository extends LUCRSURE_Repository {

	/**
	 * Table base name.
	 *
	 * @var string
	 */
	protected $table = 'branches';

	/**
	 * Column formats.
	 *
	 * @var array<string,string>
	 */
	protected $formats = array(
		'name'         => '%s',
		'code'         => '%s',
		'region'       => '%s',
		'address'      => '%s',
		'phone'        => '%s',
		'opening_time' => '%s',
		'closing_time' => '%s',
		'image_id'     => '%d',
		'amenities'    => '%s',
		'description'  => '%s',
		'is_main'      => '%d',
		'is_active'    => '%d',
		'created_at'   => '%s',
		'updated_at'   => '%s',
	);

	/**
	 * Get active branches.
	 *
	 * @return array[]
	 */
	public function active() {
		global $wpdb;
		return $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery,PluginCheck.Security.DirectDB.UnescapedDBParameter
			$wpdb->prepare(
				'SELECT * FROM %i WHERE is_active = 1 ORDER BY name ASC',
				$this->table()
			),
			ARRAY_A
		);
	}

	/**
	 * Get branches for public display, optionally filtered by ID list.
	 *
	 * @param int[] $ids Branch IDs (empty = all active).
	 * @return array[]
	 */
	public function for_display( array $ids = array() ) {
		$ids = array_values( array_filter( array_map( 'absint', $ids ) ) );
		if ( empty( $ids ) ) {
			return $this->active();
		}

		global $wpdb;
		$placeholders = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
		$prepare_args = array_merge( array( $this->table() ), $ids );
		$rows         = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
			$wpdb->prepare(
				'SELECT * FROM %i WHERE is_active = 1 AND id IN (' . $placeholders . ') ORDER BY name ASC', // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter
				...$prepare_args
			),
			ARRAY_A
		);

		if ( empty( $rows ) ) {
			return array();
		}

		$indexed = array();
		foreach ( $rows as $row ) {
			$indexed[ (int) $row['id'] ] = $row;
		}

		$ordered = array();
		foreach ( $ids as $id ) {
			if ( isset( $indexed[ $id ] ) ) {
				$ordered[] = $indexed[ $id ];
			}
		}
		return $ordered;
	}

	/**
	 * Parse branch amenities from stored text.
	 *
	 * @param array $branch Branch row.
	 * @return string[]
	 */
	public static function amenities( $branch ) {
		if ( empty( $branch['amenities'] ) ) {
			return array();
		}
		$lines = preg_split( '/\r\n|\r|\n/', (string) $branch['amenities'] );
		$out   = array();
		foreach ( $lines as $line ) {
			$line = trim( $line );
			if ( '' !== $line ) {
				$out[] = $line;
			}
		}
		return $out;
	}

	/**
	 * Resolve a branch image URL from its attachment ID.
	 *
	 * @param array  $branch Branch row.
	 * @param string $size   Image size.
	 * @return string
	 */
	public static function image_url( $branch, $size = 'medium' ) {
		if ( empty( $branch['image_id'] ) ) {
			return '';
		}
		$url = wp_get_attachment_image_url( (int) $branch['image_id'], $size );
		return $url ? $url : '';
	}
}
