<?php
/**
 * Club Management Class
 *
 * Handles CRUD operations for clubs
 *
 * @package    Karate_Club_Manager
 * @subpackage Karate_Club_Manager/includes/classes
 * @since      1.0.2
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class MACM_Club
 *
 * Manages clubs/dojos
 *
 * @since 1.0.2
 */
class MACM_Club {

	/**
	 * Create a new club
	 *
	 * @since 1.0.2
	 * @param array $data Club data.
	 * @return int|WP_Error Club ID on success, WP_Error on failure.
	 */
	public static function create( $data ) {
		global $wpdb;

		// Validate required fields.
		if ( empty( $data['name'] ) ) {
			return new WP_Error( 'missing_name', __( 'Club name is required.', 'martial-arts-club-manager' ) );
		}

		// Validate name length.
		if ( strlen( $data['name'] ) > 255 ) {
			return new WP_Error( 'name_too_long', __( 'Club name must be less than 255 characters.', 'martial-arts-club-manager' ) );
		}

		// Validate description length if provided.
		if ( ! empty( $data['description'] ) && strlen( $data['description'] ) > 1000 ) {
			return new WP_Error( 'description_too_long', __( 'Description must be less than 1000 characters.', 'martial-arts-club-manager' ) );
		}

		// Prepare data for insertion.
		$insert_data = array(
			'club_name'   => sanitize_text_field( $data['name'] ),
			'description' => ! empty( $data['description'] ) ? sanitize_textarea_field( $data['description'] ) : null,
			'is_active'   => isset( $data['is_active'] ) ? (int) $data['is_active'] : 1,
			'created_at'  => current_time( 'mysql' ),
		);

		$table_name = $wpdb->prefix . 'macm_clubs';

		// Insert into database.
		$inserted = $wpdb->insert(
			$table_name,
			$insert_data,
			array( '%s', '%s', '%d', '%s' )
		);

		if ( false === $inserted ) {
			return new WP_Error( 'db_error', __( 'Failed to create club.', 'martial-arts-club-manager' ) );
		}

		$club_id = $wpdb->insert_id;

		// Fire action hook.
		do_action( 'macm_club_created', $club_id, $insert_data );

		return $club_id;
	}

	/**
	 * Get club by ID
	 *
	 * @since 1.0.2
	 * @param int $club_id Club ID.
	 * @return object|false Club object on success, false on failure.
	 */
	public static function get( $club_id ) {
		global $wpdb;

		$table_name = $wpdb->prefix . 'macm_clubs';

		$club = $wpdb->get_row(
			$wpdb->prepare(
				'SELECT * FROM %i WHERE id = %d',
				$table_name,
				$club_id
			)
		);

		return $club ? $club : false;
	}

	/**
	 * Get all clubs
	 *
	 * @since 1.0.2
	 * @param bool $active_only Whether to return only active clubs.
	 * @return array Array of club objects.
	 */
	public static function get_all( $active_only = true ) {
		global $wpdb;

		$table_name = $wpdb->prefix . 'macm_clubs';

		if ( $active_only ) {
			$clubs = $wpdb->get_results(
				$wpdb->prepare(
					'SELECT * FROM %i WHERE is_active = 1 ORDER BY club_name ASC',
					$table_name
				)
			);
		} else {
			$clubs = $wpdb->get_results(
				$wpdb->prepare(
					'SELECT * FROM %i ORDER BY club_name ASC',
					$table_name
				)
			);
		}

		return $clubs ? $clubs : array();
	}

	/**
	 * Update club
	 *
	 * @since 1.0.2
	 * @param int   $club_id Club ID.
	 * @param array $data Club data to update.
	 * @return bool|WP_Error True on success, WP_Error on failure.
	 */
	public static function update( $club_id, $data ) {
		global $wpdb;

		// Check if club exists.
		$club = self::get( $club_id );
		if ( ! $club ) {
			return new WP_Error( 'not_found', __( 'Club not found.', 'martial-arts-club-manager' ) );
		}

		// Validate name if provided.
		if ( isset( $data['name'] ) ) {
			if ( empty( $data['name'] ) ) {
				return new WP_Error( 'missing_name', __( 'Club name is required.', 'martial-arts-club-manager' ) );
			}
			if ( strlen( $data['name'] ) > 255 ) {
				return new WP_Error( 'name_too_long', __( 'Club name must be less than 255 characters.', 'martial-arts-club-manager' ) );
			}
		}

		// Validate description if provided.
		if ( isset( $data['description'] ) && strlen( $data['description'] ) > 1000 ) {
			return new WP_Error( 'description_too_long', __( 'Description must be less than 1000 characters.', 'martial-arts-club-manager' ) );
		}

		// Prepare data for update.
		$update_data = array();
		$format      = array();

		if ( isset( $data['name'] ) ) {
			$update_data['club_name'] = sanitize_text_field( $data['name'] );
			$format[]                 = '%s';
		}

		if ( isset( $data['description'] ) ) {
			$update_data['description'] = sanitize_textarea_field( $data['description'] );
			$format[]                   = '%s';
		}

		if ( isset( $data['is_active'] ) ) {
			$update_data['is_active'] = (int) $data['is_active'];
			$format[]                 = '%d';
		}

		if ( empty( $update_data ) ) {
			return new WP_Error( 'no_data', __( 'No data to update.', 'martial-arts-club-manager' ) );
		}

		$table_name = $wpdb->prefix . 'macm_clubs';

		// Update database.
		$updated = $wpdb->update(
			$table_name,
			$update_data,
			array( 'id' => $club_id ),
			$format,
			array( '%d' )
		);

		if ( false === $updated ) {
			return new WP_Error( 'db_error', __( 'Failed to update club.', 'martial-arts-club-manager' ) );
		}

		// Fire action hook.
		do_action( 'macm_club_updated', $club_id, $update_data );

		return true;
	}

	/**
	 * Delete club
	 *
	 * Sets club_id to NULL for all members associated with this club before deleting
	 *
	 * @since 1.0.2
	 * @param int $club_id Club ID.
	 * @return bool|WP_Error True on success, WP_Error on failure.
	 */
	public static function delete( $club_id ) {
		global $wpdb;

		// Check if club exists.
		$club = self::get( $club_id );
		if ( ! $club ) {
			return new WP_Error( 'not_found', __( 'Club not found.', 'martial-arts-club-manager' ) );
		}

		// Set club_id to NULL for all members associated with this club.
		$members_table = $wpdb->prefix . 'macm_members';
		$wpdb->update(
			$members_table,
			array( 'club_id' => null ),
			array( 'club_id' => $club_id ),
			array( '%d' ),
			array( '%d' )
		);

		$table_name = $wpdb->prefix . 'macm_clubs';

		// Delete from database.
		$deleted = $wpdb->delete(
			$table_name,
			array( 'id' => $club_id ),
			array( '%d' )
		);

		if ( false === $deleted ) {
			return new WP_Error( 'db_error', __( 'Failed to delete club.', 'martial-arts-club-manager' ) );
		}

		// Fire action hook.
		do_action( 'macm_club_deleted', $club_id );

		return true;
	}

	/**
	 * Get members in a club
	 *
	 * @since 1.0.2
	 * @param int $club_id Club ID.
	 * @return array Array of member objects.
	 */
	public static function get_members( $club_id ) {
		global $wpdb;

		$members_table = $wpdb->prefix . 'macm_members';

		$members = $wpdb->get_results(
			$wpdb->prepare(
				'SELECT * FROM %i WHERE club_id = %d ORDER BY full_name ASC',
				$members_table,
				$club_id
			)
		);

		return $members ? $members : array();
	}

	/**
	 * Get member count for a club
	 *
	 * @since 1.0.2
	 * @param int $club_id Club ID.
	 * @return int Active member count.
	 */
	public static function get_member_count( $club_id ) {
		global $wpdb;

		$members_table = $wpdb->prefix . 'macm_members';

		$count = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM %i WHERE club_id = %d AND status = 'active'",
				$members_table,
				$club_id
			)
		);

		return (int) $count;
	}

	/**
	 * Check if club name already exists
	 *
	 * @since 1.0.2
	 * @param string $name Club name.
	 * @param int    $exclude_id Club ID to exclude from check (for updates).
	 * @return bool True if exists, false if not.
	 */
	public static function name_exists( $name, $exclude_id = 0 ) {
		global $wpdb;

		$table_name = $wpdb->prefix . 'macm_clubs';

		$count = $wpdb->get_var(
			$wpdb->prepare(
				'SELECT COUNT(*) FROM %i WHERE club_name = %s AND id != %d',
				$table_name,
				sanitize_text_field( $name ),
				$exclude_id
			)
		);

		return $count > 0;
	}
}
