<?php
/**
 * Warranty Controller for Warranty Cart Admin REST API
 *
 * Handles warranty product and record management REST API operations.
 *
 * @package WarrantyCart
 */

namespace WarrantyCart\REST\Controllers;

use WarrantyCart\Core\WarrantyHandler;
use WarrantyCart\REST\BaseController;
use WC_Product;
use WC_Product_Simple;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

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

/**
 * WarrantyController class
 */
class WarrantyController extends BaseController {

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->rest_base = 'admin';
	}

	/**
	 * Register routes
	 */
	public function register_routes(): void {
		// Warranty Products endpoints (WooCommerce products with warranty meta)
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/warranty-products',
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_warranty_products' ),
					'permission_callback' => array( $this, 'check_admin_permission' ),
					'args'                => $this->get_warranties_args(),
				),
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'create_warranty_product' ),
					'permission_callback' => array( $this, 'check_admin_permission' ),
					'args'                => $this->get_create_warranty_args(),
				),
			)
		);

		// Individual Warranty Product endpoints
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/warranty-products/(?P<id>\d+)',
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_warranty_product' ),
					'permission_callback' => array( $this, 'check_admin_permission' ),
					'args'                => array(
						'id' => array(
							'required'          => true,
							'type'              => 'integer',
							'description'       => __( 'Warranty product ID.', 'warranty-cart' ),
							'sanitize_callback' => 'absint',
						),
					),
				),
				array(
					'methods'             => WP_REST_Server::EDITABLE,
					'callback'            => array( $this, 'update_warranty_product' ),
					'permission_callback' => array( $this, 'check_admin_permission' ),
					'args'                => array_merge(
						array(
							'id' => array(
								'required'          => true,
								'type'              => 'integer',
								'description'       => __( 'Warranty product ID.', 'warranty-cart' ),
								'sanitize_callback' => 'absint',
							),
						),
						$this->get_create_warranty_args()
					),
				),
				array(
					'methods'             => WP_REST_Server::DELETABLE,
					'callback'            => array( $this, 'delete_warranty_product' ),
					'permission_callback' => array( $this, 'check_admin_permission' ),
					'args'                => array(
						'id' => array(
							'required'          => true,
							'type'              => 'integer',
							'description'       => __( 'Warranty product ID.', 'warranty-cart' ),
							'sanitize_callback' => 'absint',
						),
					),
				),
			)
		);

		// Warranty Records endpoints (purchased warranty instances from database)
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/warranty-records',
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_warranty_records' ),
					'permission_callback' => array( $this, 'check_admin_permission' ),
					'args'                => $this->get_warranty_records_args(),
				),
			)
		);

		// Individual Warranty Record endpoints
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/warranty-records/(?P<id>\d+)',
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_warranty_record' ),
					'permission_callback' => array( $this, 'check_admin_permission' ),
					'args'                => array(
						'id' => array(
							'required'          => true,
							'type'              => 'integer',
							'description'       => __( 'Warranty record ID.', 'warranty-cart' ),
							'sanitize_callback' => 'absint',
						),
					),
				),
				array(
					'methods'             => WP_REST_Server::EDITABLE,
					'callback'            => array( $this, 'update_warranty_record' ),
					'permission_callback' => array( $this, 'check_admin_permission' ),
					'args'                => array_merge(
						array(
							'id' => array(
								'required'          => true,
								'type'              => 'integer',
								'description'       => __( 'Warranty record ID.', 'warranty-cart' ),
								'sanitize_callback' => 'absint',
							),
						),
						$this->get_update_warranty_record_args()
					),
				),
			)
		);

		// Warranty Record renewal endpoint
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/warranty-records/(?P<id>\d+)/renew',
			array(
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'renew_warranty_record' ),
					'permission_callback' => array( $this, 'check_admin_permission' ),
					'args'                => array(
						'id' => array(
							'required'          => true,
							'type'              => 'integer',
							'description'       => __( 'Warranty record ID to renew.', 'warranty-cart' ),
							'sanitize_callback' => 'absint',
						),
					),
				),
			)
		);
	}

	/**
	 * Get warranties arguments
	 */
	private function get_warranties_args(): array {
		return array(
			'page'     => array(
				'required'    => false,
				'type'        => 'integer',
				'default'     => 1,
				'description' => __( 'Page number.', 'warranty-cart' ),
				'minimum'     => 1,
			),
			'per_page' => array(
				'required'    => false,
				'type'        => 'integer',
				'default'     => 20,
				'description' => __( 'Items per page.', 'warranty-cart' ),
				'minimum'     => 1,
				'maximum'     => 100,
			),
			'search'   => array(
				'required'          => false,
				'type'              => 'string',
				'description'       => __( 'Search term.', 'warranty-cart' ),
				'sanitize_callback' => 'sanitize_text_field',
			),
			'type'     => array(
				'required'          => false,
				'type'              => 'string',
				'enum'              => array( '', 'main_warranty', 'additional_service' ),
				'description'       => __( 'Warranty type filter.', 'warranty-cart' ),
				'sanitize_callback' => 'sanitize_text_field',
			),
		);
	}

	/**
	 * Get warranty records arguments
	 */
	private function get_warranty_records_args(): array {
		return array(
			'page'        => array(
				'required'    => false,
				'type'        => 'integer',
				'default'     => 1,
				'description' => __( 'Page number.', 'warranty-cart' ),
				'minimum'     => 1,
			),
			'per_page'    => array(
				'required'    => false,
				'type'        => 'integer',
				'default'     => 20,
				'description' => __( 'Items per page.', 'warranty-cart' ),
				'minimum'     => 1,
				'maximum'     => 100,
			),
			'search'      => array(
				'required'          => false,
				'type'              => 'string',
				'description'       => __( 'Search term.', 'warranty-cart' ),
				'sanitize_callback' => 'sanitize_text_field',
			),
			'status'      => array(
				'required'          => false,
				'type'              => 'string',
				'enum'              => array( 'active', 'expired', 'cancelled' ),
				'description'       => __( 'Warranty status filter.', 'warranty-cart' ),
				'sanitize_callback' => 'sanitize_text_field',
			),
			'customer_id' => array(
				'required'          => false,
				'type'              => 'integer',
				'description'       => __( 'Filter by customer ID.', 'warranty-cart' ),
				'sanitize_callback' => 'absint',
			),
			'order_id'    => array(
				'required'          => false,
				'type'              => 'integer',
				'description'       => __( 'Filter by order ID.', 'warranty-cart' ),
				'sanitize_callback' => 'absint',
			),
		);
	}

	/**
	 * Get update warranty record arguments
	 */
	private function get_update_warranty_record_args(): array {
		return array(
			'status'           => array(
				'required'          => false,
				'type'              => 'string',
				'enum'              => array( 'active', 'expired', 'cancelled' ),
				'description'       => __( 'Warranty status.', 'warranty-cart' ),
				'sanitize_callback' => 'sanitize_text_field',
			),
			'expiration_date'  => array(
				'required'          => false,
				'type'              => 'string',
				'format'            => 'date',
				'description'       => __( 'New expiration date (YYYY-MM-DD).', 'warranty-cart' ),
				'sanitize_callback' => 'sanitize_text_field',
			),
			'reminder_sent'    => array(
				'required'          => false,
				'type'              => 'boolean',
				'description'       => __( 'Whether reminder has been sent.', 'warranty-cart' ),
				'sanitize_callback' => 'wp_validate_boolean',
			),
			'expired_notified' => array(
				'required'          => false,
				'type'              => 'boolean',
				'description'       => __( 'Whether expiration notification has been sent.', 'warranty-cart' ),
				'sanitize_callback' => 'wp_validate_boolean',
			),
		);
	}

	/**
	 * Get create warranty arguments
	 */
	private function get_create_warranty_args(): array {
		return array(
			'name'                => array(
				'required'          => true,
				'type'              => 'string',
				'description'       => __( 'Warranty product name.', 'warranty-cart' ),
				'sanitize_callback' => 'sanitize_text_field',
			),
			'description'         => array(
				'required'          => false,
				'type'              => 'string',
				'description'       => __( 'Warranty product description.', 'warranty-cart' ),
				'sanitize_callback' => 'wp_kses_post',
			),
			'price'               => array(
				'required'    => true,
				'type'        => 'number',
				'description' => __( 'Warranty product price.', 'warranty-cart' ),
				'minimum'     => 0,
			),
			'warranty_type'       => array(
				'required'          => true,
				'type'              => 'string',
				'enum'              => array( 'main_warranty', 'additional_service' ),
				'description'       => __( 'Type of warranty product.', 'warranty-cart' ),
				'sanitize_callback' => 'sanitize_text_field',
			),
			'duration'            => array(
				'required'    => true,
				'type'        => 'integer',
				'description' => __( 'Warranty duration value.', 'warranty-cart' ),
				'minimum'     => 1,
			),
			'duration_unit'       => array(
				'required'    => true,
				'type'        => 'string',
				'enum'        => array( 'days', 'months', 'years' ),
				'description' => __( 'Warranty duration unit.', 'warranty-cart' ),
			),
			'coverage_details'    => array(
				'required'          => false,
				'type'              => 'string',
				'description'       => __( 'Warranty coverage details.', 'warranty-cart' ),
				'sanitize_callback' => 'wp_kses_post',
			),
			'associated_warranty' => array(
				'required'    => false,
				'type'        => 'integer',
				'description' => __( 'Associated main warranty ID (for services).', 'warranty-cart' ),
			),
			'service_priority'    => array(
				'required'    => false,
				'type'        => 'string',
				'enum'        => array( 'required', 'recommended', 'optional' ),
				'description' => __( 'Service priority level.', 'warranty-cart' ),
			),
		);
	}

	/**
	 * Get warranties
	 *
	 * Retrieves warranty products with pagination and filtering.
	 */
	public function get_warranties( WP_REST_Request $request ): WP_REST_Response {
		$page     = $request->get_param( 'page' );
		$per_page = $request->get_param( 'per_page' );
		$search   = $request->get_param( 'search' );
		$type     = $request->get_param( 'type' );

		// Build additional query arguments
		$query_args = array(
			'limit'   => absint( $per_page ),
			'page'    => $page,
			'orderby' => 'date',
			'order'   => 'DESC',
		);

		// Add search if provided
		if ( $search ) {
			$query_args['s'] = $search;
		}

		// Add type filter if provided
		if ( $type ) {
			$query_args['meta_query']['relation'] = 'AND';

			$query_args['meta_query'][] = array(
				'key'     => '_warranty_cart_product_type',
				'compare' => 'EXISTS',
			);
			$query_args['meta_query'][] = array(
				'key'     => '_warranty_cart_product_type',
				'value'   => $type,
				'compare' => '=',
			);
		}

		$products   = warranty_cart()->reports->get_warranty_products( $query_args );
		$warranties = array();

		foreach ( $products as $product ) {
			if ( ! $product instanceof WC_Product ) {
				continue;
			}

			$warranties[] = array(
				'id'                  => $product->get_id(),
				'name'                => $product->get_name(),
				'description'         => $product->get_description(),
				'price'               => $product->get_price(),
				'warranty_type'       => $product->get_meta( '_warranty_cart_product_type', true ),
				'duration'            => $product->get_meta( '_warranty_cart_duration', true ),
				'duration_unit'       => $product->get_meta( '_warranty_cart_duration_unit', true ),
				'coverage_details'    => $product->get_meta( '_warranty_cart_coverage_details', true ),
				'associated_warranty' => $product->get_meta( '_warranty_cart_associated_warranty', true ),
				'service_priority'    => $product->get_meta( '_warranty_cart_service_priority', true ),
				'status'              => $product->get_status(),
				'stock_status'        => $product->get_stock_status(),
			);
		}

		// Get total count for pagination
		$count_args = $query_args;
		unset( $count_args['limit'], $count_args['page'] );
		$count_args['return'] = 'ids';

		$currency         = get_woocommerce_currency_symbol();
		$all_product_ids  = warranty_cart()->reports->get_warranty_product_ids( $count_args );
		$total_warranties = count( $all_product_ids );
		$total_pages      = $per_page > 0 ? ceil( $total_warranties / $per_page ) : 1;

		return $this->success_response(
			array(
				'warranties'  => $warranties,
				'total'       => $total_warranties,
				'page'        => $page,
				'per_page'    => $per_page,
				'total_pages' => $total_pages,
				'currency'    => $currency,
			)
		);
	}

	/**
	 * Get single warranty product
	 *
	 * Retrieves detailed information for a specific warranty product.
	 */
	public function get_warranty_product( WP_REST_Request $request ) {
		$warranty_id = $request->get_param( 'id' );

		$product = wc_get_product( $warranty_id );
		if ( ! $product ) {
			return $this->error_response( __( 'Warranty product not found.', 'warranty-cart' ), 404 );
		}

		$warranty_type = $product->get_meta( '_warranty_cart_product_type', true );
		if ( ! $warranty_type ) {
			return $this->error_response( __( 'Product is not a warranty product.', 'warranty-cart' ), 404 );
		}

		$warranty = array(
			'id'                  => $product->get_id(),
			'name'                => $product->get_name(),
			'description'         => $product->get_description(),
			'price'               => $product->get_price(),
			'warranty_type'       => $warranty_type,
			'duration'            => (int) $product->get_meta( '_warranty_cart_duration', true ),
			'duration_unit'       => $product->get_meta( '_warranty_cart_duration_unit', true ),
			'coverage_details'    => $product->get_meta( '_warranty_cart_coverage_details', true ),
			'associated_warranty' => (int) $product->get_meta( '_warranty_cart_associated_warranty', true ),
			'service_priority'    => $product->get_meta( '_warranty_cart_service_priority', true ),
			'status'              => $product->get_status(),
			'stock_status'        => $product->get_stock_status(),
			'regular_price'       => $product->get_regular_price(),
			'sale_price'          => $product->get_sale_price(),
			'manage_stock'        => $product->get_manage_stock(),
			'stock_quantity'      => $product->get_stock_quantity(),
		);

		return $this->success_response( $warranty );
	}

	/**
	 * Create warranty product
	 *
	 * Creates a new warranty product with the provided data.
	 */
	public function create_warranty_product( WP_REST_Request $request ) {
		$name                = $request->get_param( 'name' );
		$description         = $request->get_param( 'description' );
		$price               = $request->get_param( 'price' );
		$warranty_type       = $request->get_param( 'warranty_type' );
		$duration            = $request->get_param( 'duration' );
		$duration_unit       = $request->get_param( 'duration_unit' );
		$coverage_details    = $request->get_param( 'coverage_details' );
		$associated_warranty = $request->get_param( 'associated_warranty' );
		$service_priority    = $request->get_param( 'service_priority' );

		// Create new WooCommerce product
		$product = new WC_Product_Simple();
		$product->set_name( $name );
		$product->set_description( $description );
		$product->set_regular_price( $price );
		$product->set_status( 'publish' );
		$product->set_catalog_visibility( 'hidden' ); // Hide from catalog
		$product->set_virtual( true ); // Virtual product
		$product->set_downloadable( false );

		// Save the product
		$product_id = $product->save();

		if ( ! $product_id ) {
			return $this->error_response( __( 'Failed to create warranty product.', 'warranty-cart' ), 500 );
		}

		// Set warranty meta data
		$product->update_meta_data( '_warranty_cart_product_type', $warranty_type );
		$product->update_meta_data( '_warranty_cart_duration', $duration );
		$product->update_meta_data( '_warranty_cart_duration_unit', $duration_unit );
		$product->update_meta_data( '_warranty_cart_coverage_details', $coverage_details );

		if ( $associated_warranty ) {
			$product->update_meta_data( '_warranty_cart_associated_warranty', $associated_warranty );
		}

		if ( $service_priority ) {
			$product->update_meta_data( '_warranty_cart_service_priority', $service_priority );
		}

		$product->save();

		$warranty = array(
			'id'                  => $product_id,
			'name'                => $name,
			'description'         => $description,
			'price'               => $price,
			'warranty_type'       => $warranty_type,
			'duration'            => $duration,
			'duration_unit'       => $duration_unit,
			'coverage_details'    => $coverage_details,
			'associated_warranty' => $associated_warranty,
			'service_priority'    => $service_priority,
			'status'              => 'publish',
		);

		return $this->success_response( $warranty, 201 );
	}

	/**
	 * Update warranty product
	 *
	 * Updates an existing warranty product with new data.
	 */
	public function update_warranty_product( WP_REST_Request $request ) {
		$warranty_id = $request->get_param( 'id' );

		$product = wc_get_product( $warranty_id );
		if ( ! $product ) {
			return $this->error_response( __( 'Warranty product not found.', 'warranty-cart' ), 404 );
		}

		$warranty_type = $product->get_meta( '_warranty_cart_product_type', true );
		if ( ! $warranty_type ) {
			return $this->error_response( __( 'Product is not a warranty product.', 'warranty-cart' ), 404 );
		}

		// Update basic product fields
		$name = $request->get_param( 'name' );
		if ( null !== $name ) {
			$product->set_name( $name );
		}

		$description = $request->get_param( 'description' );
		if ( null !== $description ) {
			$product->set_description( $description );
		}

		$price = $request->get_param( 'price' );
		if ( null !== $price ) {
			$product->set_regular_price( $price );
		}

		// Update warranty meta fields
		$warranty_type_param = $request->get_param( 'warranty_type' );
		if ( null !== $warranty_type_param ) {
			$product->update_meta_data( '_warranty_cart_product_type', $warranty_type_param );
		}

		$duration = $request->get_param( 'duration' );
		if ( null !== $duration ) {
			$product->update_meta_data( '_warranty_cart_duration', $duration );
		}

		$duration_unit = $request->get_param( 'duration_unit' );
		if ( null !== $duration_unit ) {
			$product->update_meta_data( '_warranty_cart_duration_unit', $duration_unit );
		}

		$coverage_details = $request->get_param( 'coverage_details' );
		if ( null !== $coverage_details ) {
			$product->update_meta_data( '_warranty_cart_coverage_details', $coverage_details );
		}

		$associated_warranty = $request->get_param( 'associated_warranty' );
		if ( null !== $associated_warranty ) {
			$product->update_meta_data( '_warranty_cart_associated_warranty', $associated_warranty );
		}

		$service_priority = $request->get_param( 'service_priority' );
		if ( null !== $service_priority ) {
			$product->update_meta_data( '_warranty_cart_service_priority', $service_priority );
		}

		$product->save();

		// Return updated warranty data
		$warranty = array(
			'id'                  => $product->get_id(),
			'name'                => $product->get_name(),
			'description'         => $product->get_description(),
			'price'               => $product->get_price(),
			'warranty_type'       => $product->get_meta( '_warranty_cart_product_type', true ),
			'duration'            => (int) $product->get_meta( '_warranty_cart_duration', true ),
			'duration_unit'       => $product->get_meta( '_warranty_cart_duration_unit', true ),
			'coverage_details'    => $product->get_meta( '_warranty_cart_coverage_details', true ),
			'associated_warranty' => (int) $product->get_meta( '_warranty_cart_associated_warranty', true ),
			'service_priority'    => $product->get_meta( '_warranty_cart_service_priority', true ),
			'status'              => $product->get_status(),
		);

		return $this->success_response( $warranty );
	}

	/**
	 * Delete warranty product
	 *
	 * Deletes a warranty product if it has no associated orders.
	 */
	public function delete_warranty_product( WP_REST_Request $request ) {
		$warranty_id = $request->get_param( 'id' );

		$product = wc_get_product( $warranty_id );
		if ( ! $product ) {
			return $this->error_response( __( 'Warranty product not found.', 'warranty-cart' ), 404 );
		}

		$warranty_type = $product->get_meta( '_warranty_cart_product_type', true );
		if ( ! $warranty_type ) {
			return $this->error_response( __( 'Product is not a warranty product.', 'warranty-cart' ), 404 );
		}

		// Check if warranty has associated orders
		$order_count = wc_get_orders(
			array(
				'limit'      => 1,
				'return'     => 'ids',
				'meta_query' => array(
					array(
						'key'     => '_product_id',
						'value'   => $warranty_id,
						'compare' => '=',
					),
				),
			)
		);

		if ( ! empty( $order_count ) ) {
			return $this->error_response( __( 'Cannot delete warranty product that has been purchased.', 'warranty-cart' ), 400 );
		}

		// Delete the product
		$deleted = $product->delete( true );
		if ( ! $deleted ) {
			return $this->error_response( __( 'Failed to delete warranty product.', 'warranty-cart' ), 500 );
		}

		return $this->success_response(
			array(
				'message' => __( 'Warranty product deleted successfully.', 'warranty-cart' ),
				'id'      => $warranty_id,
			)
		);
	}

	/**
	 * Get warranty records
	 *
	 * Retrieves warranty records with pagination and filtering.
	 */
	public function get_warranty_records( WP_REST_Request $request ): WP_REST_Response {
		global $wpdb;

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

		$page        = $request->get_param( 'page' );
		$per_page    = $request->get_param( 'per_page' );
		$search      = $request->get_param( 'search' );
		$status      = $request->get_param( 'status' );
		$customer_id = $request->get_param( 'customer_id' );
		$order_id    = $request->get_param( 'order_id' );

		// Build query with JOINs for customer and product data
		$query        = "SELECT w.*,
			u.user_email as customer_email,
			CONCAT(u.first_name, ' ', u.last_name) as customer_name,
			p.post_title as product_name,
			pm.meta_value as product_sku
		FROM " . $table_name . ' w
		LEFT JOIN ' . $wpdb->users . ' u ON w.customer_id = u.ID
		LEFT JOIN ' . $wpdb->posts . ' p ON w.product_id = p.ID
		LEFT JOIN ' . $wpdb->postmeta . " pm ON w.product_id = pm.post_id AND pm.meta_key = '_sku'
		WHERE 1=1";
		$query_params = array();

		// Add filters
		if ( $status ) {
			$query         .= ' AND status = %s';
			$query_params[] = $status;
		}

		if ( $customer_id ) {
			$query         .= ' AND customer_id = %d';
			$query_params[] = $customer_id;
		}

		if ( $order_id ) {
			$query         .= ' AND order_id = %d';
			$query_params[] = $order_id;
		}

		if ( $search ) {
			$query       .= " AND (CONCAT(u.first_name, ' ', u.last_name) LIKE %s OR u.user_email LIKE %s OR p.post_title LIKE %s OR pm.meta_value LIKE %s)";
			$search_param = '%' . $wpdb->esc_like( $search ) . '%';
			$query_params = array_merge( $query_params, array( $search_param, $search_param, $search_param, $search_param ) );
		}

		// Add pagination
		$offset         = ( $page - 1 ) * $per_page;
		$query         .= ' ORDER BY created_at DESC LIMIT %d OFFSET %d';
		$query_params[] = $per_page;
		$query_params[] = $offset;

		// Execute query
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
		$warranty_records = $wpdb->get_results( $wpdb->prepare( $query, $query_params ) );

		// Get total count
		$count_query = str_replace( 'SELECT *', 'SELECT COUNT(*)', $query );
		$count_query = preg_replace( '/ORDER BY.*LIMIT.*/', '', $count_query );
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
		$total_count = $wpdb->get_var( $wpdb->prepare( $count_query, array_slice( $query_params, 0, - 2 ) ) );

		$total_pages = $per_page > 0 ? ceil( $total_count / $per_page ) : 1;

		// Format records
		$records = array();
		foreach ( $warranty_records as $record ) {
			$records[] = array(
				'id'                => (int) $record->id,
				'order_id'          => (int) $record->order_id,
				'customer_id'       => (int) $record->customer_id,
				'customer_name'     => $record->customer_name,
				'customer_email'    => $record->customer_email,
				'product_id'        => (int) $record->product_id,
				'product_name'      => $record->product_name,
				'product_sku'       => $record->product_sku,
				'warranty_type'     => $record->warranty_type,
				'duration'          => (int) $record->duration,
				'duration_unit'     => $record->duration_unit,
				'purchase_date'     => $record->purchase_date,
				'expiration_date'   => $record->expiration_date,
				'purchase_price'    => (float) $record->purchase_price,
				'currency'          => $record->currency,
				'payment_method'    => $record->payment_method,
				'status'            => $record->status,
				'source'            => $record->source,
				'coverage_details'  => $record->coverage_details,
				'reminder_sent'     => (bool) $record->reminder_sent,
				'expired_notified'  => (bool) $record->expired_notified,
				'renewal_count'     => (int) $record->renewal_count,
				'last_renewal_date' => $record->last_renewal_date,
				'created_at'        => $record->created_at,
				'updated_at'        => $record->updated_at,
			);
		}

		return $this->success_response(
			array(
				'records'     => $records,
				'total'       => (int) $total_count,
				'page'        => $page,
				'per_page'    => $per_page,
				'total_pages' => $total_pages,
			)
		);
	}

	/**
	 * Get single warranty record
	 *
	 * Retrieves detailed information for a specific warranty record.
	 */
	public function get_warranty_record( WP_REST_Request $request ) {
		global $wpdb;

		$table_name  = $wpdb->prefix . 'warranty_cart_warranties';
		$warranty_id = $request->get_param( 'id' );

		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$record = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table_name} WHERE id = %d", $warranty_id ) );

		if ( ! $record ) {
			return $this->error_response( __( 'Warranty record not found.', 'warranty-cart' ), 404 );
		}

		$warranty = array(
			'id'                => (int) $record->id,
			'order_id'          => (int) $record->order_id,
			'customer_id'       => (int) $record->customer_id,
			'customer_name'     => $record->customer_name,
			'customer_email'    => $record->customer_email,
			'product_id'        => (int) $record->product_id,
			'product_name'      => $record->product_name,
			'product_sku'       => $record->product_sku,
			'warranty_type'     => $record->warranty_type,
			'duration'          => (int) $record->duration,
			'duration_unit'     => $record->duration_unit,
			'purchase_date'     => $record->purchase_date,
			'expiration_date'   => $record->expiration_date,
			'purchase_price'    => (float) $record->purchase_price,
			'currency'          => $record->currency,
			'payment_method'    => $record->payment_method,
			'status'            => $record->status,
			'source'            => $record->source,
			'coverage_details'  => $record->coverage_details,
			'reminder_sent'     => (bool) $record->reminder_sent,
			'expired_notified'  => (bool) $record->expired_notified,
			'renewal_count'     => (int) $record->renewal_count,
			'last_renewal_date' => $record->last_renewal_date,
			'created_at'        => $record->created_at,
			'updated_at'        => $record->updated_at,
		);

		return $this->success_response( $warranty );
	}

	/**
	 * Update warranty record
	 *
	 * Updates an existing warranty record with new data.
	 */
	public function update_warranty_record( WP_REST_Request $request ) {
		global $wpdb;

		$table_name  = $wpdb->prefix . 'warranty_cart_warranties';
		$warranty_id = $request->get_param( 'id' );

		// Check if record exists
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$existing = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$table_name} WHERE id = %d", $warranty_id ) );

		if ( ! $existing ) {
			return $this->error_response( __( 'Warranty record not found.', 'warranty-cart' ), 404 );
		}

		// Prepare update data
		$update_data   = array();
		$update_format = array();

		$status = $request->get_param( 'status' );
		if ( null !== $status ) {
			$update_data['status'] = $status;
			$update_format[]       = '%s';
		}

		$expiration_date = $request->get_param( 'expiration_date' );
		if ( null !== $expiration_date ) {
			$update_data['expiration_date'] = $expiration_date;
			$update_format[]                = '%s';
		}

		$reminder_sent = $request->get_param( 'reminder_sent' );
		if ( null !== $reminder_sent ) {
			$update_data['reminder_sent'] = $reminder_sent ? 1 : 0;
			$update_format[]              = '%d';
		}

		$expired_notified = $request->get_param( 'expired_notified' );
		if ( null !== $expired_notified ) {
			$update_data['expired_notified'] = $expired_notified ? 1 : 0;
			$update_format[]                 = '%d';
		}

		if ( empty( $update_data ) ) {
			return $this->error_response( __( 'No valid fields to update.', 'warranty-cart' ), 400 );
		}

		$update_data['updated_at'] = current_time( 'mysql' );
		$update_format[]           = '%s';

		// Update record
		$result = $wpdb->update(
			$table_name,
			$update_data,
			array( 'id' => $warranty_id ),
			$update_format,
			array( '%d' )
		);

		if ( false === $result ) {
			return $this->error_response( __( 'Failed to update warranty record.', 'warranty-cart' ), 500 );
		}

		// Get updated record
		$updated_record = $this->get_warranty_record( $request );
		if ( is_wp_error( $updated_record ) ) {
			return $updated_record;
		}

		return $this->success_response(
			array(
				'message' => __( 'Warranty record updated successfully.', 'warranty-cart' ),
				'record'  => $updated_record->get_data(),
			)
		);
	}

	/**
	 * Renew warranty record
	 *
	 * Renews an existing warranty record by extending its expiration date.
	 */
	public function renew_warranty_record( WP_REST_Request $request ) {
		$warranty_id = $request->get_param( 'id' );

		// Check if WarrantyHandler has the renew method
		if ( ! method_exists( WarrantyHandler::class, 'renew_warranty' ) ) {
			return $this->error_response( __( 'Warranty renewal is not available.', 'warranty-cart' ), 400 );
		}

		$handler = new WarrantyHandler();
		$success = $handler->renew_warranty( $warranty_id );

		if ( $success ) {
			return $this->success_response(
				array(
					'message' => __( 'Warranty renewed successfully.', 'warranty-cart' ),
					'id'      => $warranty_id,
				)
			);
		}

		return $this->error_response( __( 'Failed to renew warranty.', 'warranty-cart' ), 500 );
	}

	/**
	 * Get warranty products (alias for get_warranties)
	 */
	public function get_warranty_products( WP_REST_Request $request ): WP_REST_Response {
		return $this->get_warranties( $request );
	}
}
