<?php
/**
 * Pickup Locations REST API Controller
 *
 * @package WooNooW
 */

namespace WooNooW\Api;

use WP_REST_Controller;
use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;

class PickupLocationsController extends WP_REST_Controller {

	/**
	 * Register routes
	 */
	public function register_routes() {
		$namespace = 'woonoow/v1';

		// Get all pickup locations
		register_rest_route(
			$namespace,
			'/settings/pickup-locations',
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_locations' ),
					'permission_callback' => array( $this, 'check_permission' ),
				),
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'create_location' ),
					'permission_callback' => array( $this, 'check_permission' ),
				),
			)
		);

		// Update/Delete specific location
		register_rest_route(
			$namespace,
			'/settings/pickup-locations/(?P<id>[a-zA-Z0-9_-]+)',
			array(
				array(
					'methods'             => WP_REST_Server::EDITABLE,
					'callback'            => array( $this, 'update_location' ),
					'permission_callback' => array( $this, 'check_permission' ),
				),
				array(
					'methods'             => WP_REST_Server::DELETABLE,
					'callback'            => array( $this, 'delete_location' ),
					'permission_callback' => array( $this, 'check_permission' ),
				),
			)
		);

		// Toggle location
		register_rest_route(
			$namespace,
			'/settings/pickup-locations/(?P<id>[a-zA-Z0-9_-]+)/toggle',
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'toggle_location' ),
				'permission_callback' => array( $this, 'check_permission' ),
			)
		);
	}

	/**
	 * Check permission
	 */
	public function check_permission() {
		return current_user_can( 'manage_woocommerce' );
	}

	/**
	 * Get all pickup locations
	 */
	public function get_locations( WP_REST_Request $request ) {
		$locations = get_option( 'woonoow_pickup_locations', array() );
		return new WP_REST_Response( array_values( $locations ), 200 );
	}

	/**
	 * Create pickup location
	 */
	public function create_location( WP_REST_Request $request ) {
		try {
			$locations = get_option( 'woonoow_pickup_locations', array() );
			
			$id       = uniqid( 'loc_' );
			$location = array(
				'id'       => $id,
				'name'     => sanitize_text_field( $request->get_param( 'name' ) ),
				'address'  => sanitize_text_field( $request->get_param( 'address' ) ),
				'city'     => sanitize_text_field( $request->get_param( 'city' ) ),
				'state'    => sanitize_text_field( $request->get_param( 'state' ) ),
				'postcode' => sanitize_text_field( $request->get_param( 'postcode' ) ),
				'phone'    => sanitize_text_field( $request->get_param( 'phone' ) ),
				'hours'    => sanitize_text_field( $request->get_param( 'hours' ) ),
				'enabled'  => true,
			);

			$locations[ $id ] = $location;
			update_option( 'woonoow_pickup_locations', $locations );

			return new WP_REST_Response( $location, 201 );
		} catch ( \Exception $e ) {
			return new WP_REST_Response(
				array(
					'error'   => 'create_failed',
					'message' => $e->getMessage(),
				),
				500
			);
		}
	}

	/**
	 * Update pickup location
	 */
	public function update_location( WP_REST_Request $request ) {
		try {
			$id        = $request->get_param( 'id' );
			$locations = get_option( 'woonoow_pickup_locations', array() );

			if ( ! isset( $locations[ $id ] ) ) {
				return new WP_REST_Response(
					array(
						'error'   => 'not_found',
						'message' => __( 'Location not found', 'woonoow' ),
					),
					404
				);
			}

			$location = array(
				'id'       => $id,
				'name'     => sanitize_text_field( $request->get_param( 'name' ) ),
				'address'  => sanitize_text_field( $request->get_param( 'address' ) ),
				'city'     => sanitize_text_field( $request->get_param( 'city' ) ),
				'state'    => sanitize_text_field( $request->get_param( 'state' ) ),
				'postcode' => sanitize_text_field( $request->get_param( 'postcode' ) ),
				'phone'    => sanitize_text_field( $request->get_param( 'phone' ) ),
				'hours'    => sanitize_text_field( $request->get_param( 'hours' ) ),
				'enabled'  => $locations[ $id ]['enabled'], // Preserve enabled status
			);

			$locations[ $id ] = $location;
			update_option( 'woonoow_pickup_locations', $locations );

			return new WP_REST_Response( $location, 200 );
		} catch ( \Exception $e ) {
			return new WP_REST_Response(
				array(
					'error'   => 'update_failed',
					'message' => $e->getMessage(),
				),
				500
			);
		}
	}

	/**
	 * Delete pickup location
	 */
	public function delete_location( WP_REST_Request $request ) {
		try {
			$id        = $request->get_param( 'id' );
			$locations = get_option( 'woonoow_pickup_locations', array() );

			if ( ! isset( $locations[ $id ] ) ) {
				return new WP_REST_Response(
					array(
						'error'   => 'not_found',
						'message' => __( 'Location not found', 'woonoow' ),
					),
					404
				);
			}

			unset( $locations[ $id ] );
			update_option( 'woonoow_pickup_locations', $locations );

			return new WP_REST_Response(
				array(
					'success' => true,
					'message' => __( 'Location deleted', 'woonoow' ),
				),
				200
			);
		} catch ( \Exception $e ) {
			return new WP_REST_Response(
				array(
					'error'   => 'delete_failed',
					'message' => $e->getMessage(),
				),
				500
			);
		}
	}

	/**
	 * Toggle pickup location
	 */
	public function toggle_location( WP_REST_Request $request ) {
		try {
			$id        = $request->get_param( 'id' );
			$enabled   = rest_sanitize_boolean( $request->get_param( 'enabled' ) );
			$locations = get_option( 'woonoow_pickup_locations', array() );

			if ( ! isset( $locations[ $id ] ) ) {
				return new WP_REST_Response(
					array(
						'error'   => 'not_found',
						'message' => __( 'Location not found', 'woonoow' ),
					),
					404
				);
			}

			$locations[ $id ]['enabled'] = $enabled;
			update_option( 'woonoow_pickup_locations', $locations );

			return new WP_REST_Response(
				array(
					'success' => true,
					'enabled' => $enabled,
					'message' => $enabled 
						? __( 'Location enabled', 'woonoow' )
						: __( 'Location disabled', 'woonoow' ),
				),
				200
			);
		} catch ( \Exception $e ) {
			return new WP_REST_Response(
				array(
					'error'   => 'toggle_failed',
					'message' => $e->getMessage(),
				),
				500
			);
		}
	}
}
