<?php
/**
 * Tenant repository.
 *
 * @package KGV\VereinManager
 */

namespace KGV\VereinManager\Repositories;

use KGV\VereinManager\Schema;

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

class TenantRepository extends AbstractRepository {

	/**
	 * Resolve table name.
	 *
	 * @return string
	 */
	protected function resolve_table() {
		return Schema::table( 'tenants' );
	}

	/**
	 * Search tenant list.
	 *
	 * @param array $args Query arguments.
	 * @return array
	 */
	public function search( $args = array() ) {
		$search  = isset( $args['s'] ) ? sanitize_text_field( wp_unslash( $args['s'] ) ) : '';
		$status  = isset( $args['status'] ) ? sanitize_key( wp_unslash( $args['status'] ) ) : '';
		$orderby = $this->sanitize_orderby( isset( $args['orderby'] ) ? sanitize_key( wp_unslash( $args['orderby'] ) ) : 'last_name', array( 'last_name', 'first_name', 'contract_start', 'is_active', 'created_at' ), 'last_name' );
		$order   = $this->sanitize_order( isset( $args['order'] ) ? sanitize_key( wp_unslash( $args['order'] ) ) : 'ASC' );

		$parcel_tenants = Schema::table( 'parcel_tenants' );

		$sql = "SELECT t.*, (SELECT COUNT(*) FROM {$parcel_tenants} pt WHERE pt.tenant_id = t.id) AS parcel_count
			FROM {$this->table} t
			WHERE 1=1";

		$params = array();

		if ( '' !== $search ) {
			$like     = '%' . $this->wpdb->esc_like( $search ) . '%';
			$sql     .= ' AND (t.first_name LIKE %s OR t.last_name LIKE %s OR t.email LIKE %s OR t.phone LIKE %s)';
			$params[] = $like;
			$params[] = $like;
			$params[] = $like;
			$params[] = $like;
		}

		if ( in_array( $status, array( 'active', 'inactive' ), true ) ) {
			$sql .= ' AND t.is_active = ' . ( 'active' === $status ? '1' : '0' );
		}

		$sql .= " ORDER BY t.{$orderby} {$order}, t.id DESC";

		if ( ! empty( $params ) ) {
			return $this->wpdb->get_results( $this->wpdb->prepare( $sql, $params ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
		}

		return $this->wpdb->get_results( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery
	}

	/**
	 * Save or update tenant.
	 *
	 * @param array $data Tenant data.
	 * @param int   $id   Optional ID.
	 * @return int|false
	 */
	public function save( $data, $id = 0 ) {
		$payload = array(
			'first_name'     => $data['first_name'],
			'last_name'      => $data['last_name'],
			'address'        => $data['address'],
			'phone'          => $data['phone'],
			'email'          => $data['email'],
			'contract_start' => $data['contract_start'],
			'contract_end'   => $data['contract_end'] ? $data['contract_end'] : null,
			'is_active'      => $data['is_active'],
			'note'           => $data['note'],
			'updated_at'     => $this->now(),
		);

		$formats = array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s' );

		if ( $id > 0 ) {
			$this->wpdb->update( $this->table, $payload, array( 'id' => $id ), $formats, array( '%d' ) );
			return $id;
		}

		$payload['created_at'] = $this->now();
		$this->wpdb->insert( $this->table, $payload, array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s' ) );

		return $this->wpdb->insert_id;
	}

	/**
	 * Return active tenants for selection lists.
	 *
	 * @return array
	 */
	public function all_active() {
		$sql = "SELECT * FROM {$this->table} WHERE is_active = 1 ORDER BY last_name ASC, first_name ASC";
		return $this->wpdb->get_results( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery
	}
}
