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

namespace KGV\VereinManager\Repositories;

use KGV\VereinManager\Schema;

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

class SectionRepository extends AbstractRepository {

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

	/**
	 * Search section 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'] ) ) : 'name', array( 'name', 'status', 'created_at', 'updated_at' ), 'name' );
		$order   = $this->sanitize_order( isset( $args['order'] ) ? sanitize_key( wp_unslash( $args['order'] ) ) : 'ASC' );

		$sql    = "SELECT * FROM {$this->table} WHERE 1=1";
		$params = array();

		if ( '' !== $search ) {
			$like     = '%' . $this->wpdb->esc_like( $search ) . '%';
			$sql     .= ' AND (name LIKE %s OR description LIKE %s)';
			$params[] = $like;
			$params[] = $like;
		}

		if ( in_array( $status, array( 'active', 'inactive' ), true ) ) {
			$sql     .= ' AND status = %s';
			$params[] = $status;
		}

		$sql .= " ORDER BY {$orderby} {$order}";

		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 a section.
	 *
	 * @param array $data Section data.
	 * @param int   $id   Optional ID.
	 * @return int|false
	 */
	public function save( $data, $id = 0 ) {
		$payload = array(
			'name'        => $data['name'],
			'description' => $data['description'],
			'status'      => $data['status'],
			'updated_at'  => $this->now(),
		);

		$formats = array( '%s', '%s', '%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' ) );

		return $this->wpdb->insert_id;
	}

	/**
	 * Check if a section name already exists.
	 *
	 * @param string $name       Section name.
	 * @param int    $exclude_id Optional ID to exclude.
	 * @return bool
	 */
	public function name_exists( $name, $exclude_id = 0 ) {
		$sql = "SELECT COUNT(*) FROM {$this->table} WHERE name = %s";

		if ( $exclude_id > 0 ) {
			$sql .= ' AND id != %d';
			return (int) $this->wpdb->get_var( $this->wpdb->prepare( $sql, $name, $exclude_id ) ) > 0; // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
		}

		return (int) $this->wpdb->get_var( $this->wpdb->prepare( $sql, $name ) ) > 0; // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
	}

	/**
	 * Lightweight options list.
	 *
	 * @param bool $active_only Restrict to active sections.
	 * @return array
	 */
	public function all_for_options( $active_only = false ) {
		$sql = "SELECT * FROM {$this->table}";

		if ( $active_only ) {
			$sql .= " WHERE status = 'active'";
		}

		$sql .= ' ORDER BY name ASC';

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

	/**
	 * Check whether section still has related records.
	 *
	 * @param int $id Section ID.
	 * @return bool
	 */
	public function is_in_use( $id ) {
		$parcel_count = (int) $this->wpdb->get_var( $this->wpdb->prepare( 'SELECT COUNT(*) FROM ' . Schema::table( 'parcels' ) . ' WHERE section_id = %d', $id ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
		$meter_count  = (int) $this->wpdb->get_var( $this->wpdb->prepare( 'SELECT COUNT(*) FROM ' . Schema::table( 'meters' ) . ' WHERE section_id = %d', $id ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

		return $parcel_count > 0 || $meter_count > 0;
	}
}
