<?php
/**
 * Event Design Controller
 *
 * Handles event design CRUD operations including file uploads for the Gift Card plugin.
 *
 * @package     SGC\eGiftCard
 * @subpackage  Http\Controller
 * @since       1.0.0
 */

namespace SGC\eGiftCard\Http\Controller;

use SGC\eGiftCard\Http\Request\ValidatorHandler;
use SGC\eGiftCard\Http\Model\GiftEvent;

/**
 * Class EventDesignController
 *
 * Controller for handling event design operations.
 *
 * @since 1.0.0
 */
class EventDesignController extends BaseController {

	/**
	 * List all event designs
	 *
	 * Retrieves all event designs and occasions from the database.
	 *
	 * @since 1.0.0
	 * @param \WP_REST_Request $request The REST API request.
	 * @return \WP_REST_Response The response containing event data.
	 */
	public function index( \WP_REST_Request $request ) {
		// Verify user capabilities.
		if ( ! current_user_can( 'manage_options' ) ) {
			return $this->response( 'Permission denied', 403 );
		}

		$gift_event = GiftEvent::getInstance();
		$data       = $gift_event::all();
		$occasions  = self::get_event_list();

		return $this->response(
			array(
				'event_data' => $data,
				'occasions'  => $occasions,
			)
		);
	}

	/**
	 * Add new event design
	 *
	 * Handle the form data and insert into database, including file uploads.
	 *
	 * @since 1.0.0
	 * @return \WP_REST_Response Response data.
	 */
	public function add_event_info() {
		// Verify user capabilities.
		if ( ! current_user_can( 'manage_options' ) ) {
			return $this->response( 'Permission denied', 403 );
		}

		// Validate the input fields.
		$errors = ValidatorHandler::validateEventDesignRequest( $this->request );

		if ( count( $errors ) > 0 ) {
			return $this->response( $errors, 400 );
		}

		// Get form data from the request with proper sanitization.
		$event_name      = sanitize_text_field( wp_unslash( $this->request->get( 'event_name' ) ) );
		$design_name     = sanitize_text_field( wp_unslash( $this->request->get( 'design_name' ) ) );
		$event_file_type = sanitize_text_field( wp_unslash( $this->request->get( 'event_file_type' ) ) );
		$place_holder    = '';

		// Handle event file upload.
		$event_file = self::handle_file_upload( 'event_file' );
		if ( is_wp_error( $event_file ) ) {
			return $this->response( $event_file->get_error_message(), 400 );
		}

		// Handle placeholder upload (if the file type is video).
		if ( 'video' === $event_file_type ) {
			$place_holder = $this->handle_file_upload( 'place_holder' );
			if ( is_wp_error( $place_holder ) ) {
				// Clean up the already uploaded event file on error.
				$this->remove_uploaded_file( $event_file );
				return $this->response( $place_holder->get_error_message(), 400 );
			}
		}

		$gift_event = GiftEvent::getInstance();

		$data = array(
			'event_name'      => $event_name,
			'design_name'     => $design_name,
			'event_file'      => $event_file,
			'event_file_type' => $event_file_type,
			'place_holder'    => $place_holder,
			'created_at'      => current_time( 'mysql' ),
		);

		$result = $gift_event->store( $data );

		if ( $result ) {
			return $this->response( 'Event design added successfully', 200 );
		} else {
			// Clean up uploaded files on database failure.
			$this->remove_uploaded_file( $event_file );
			if ( ! empty( $place_holder ) ) {
				$this->remove_uploaded_file( $place_holder );
			}
			return $this->response( 'Failed to add event design', 500 );
		}
	}

	/**
	 * Update existing event design
	 *
	 * Handle the form data and update the database, including file uploads.
	 *
	 * @since 1.0.0
	 * @return \WP_REST_Response Response data.
	 */
	public function update_event_info() {
		// Verify user capabilities.
		if ( ! current_user_can( 'manage_options' ) ) {
			return $this->response( 'Permission denied', 403 );
		}

		// Verify nonce for security.
		if ( !empty($_SERVER['HTTP_X_WP_NONCE']) && ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_WP_NONCE'] ) ), 'wp_rest') ) {
			return $this->response( 'Nonce verification failed', 403 );
		}

		// Validate the input fields.
		$errors = ValidatorHandler::validateEventDesignRequest( $this->request );

		if ( count( $errors ) > 0 ) {
			return $this->response( $errors, 400 );
		}

		// Get form data from the request with proper sanitization.
		$id              = absint( $this->request->get( 'id' ) );
		$event_name      = sanitize_text_field( wp_unslash( $this->request->get( 'event_name' ) ) );
		$design_name     = sanitize_text_field( wp_unslash( $this->request->get( 'design_name' ) ) );
		$event_file_type = sanitize_text_field( wp_unslash( $this->request->get( 'event_file_type' ) ) );
		$place_holder    = '';

		// Fetch the existing record from the database.
		$gift_event     = GiftEvent::getInstance();
		$existing_event = $gift_event->find( $id );

		// Get the WordPress upload directory.
		$upload_dir  = wp_upload_dir();
		$upload_path = $upload_dir['basedir'] . '/' . SMART_GIFT_CARD_PLUGIN_ASSET_ID;

		if ( ! $existing_event ) {
			return $this->response( 'Event not found', 404 );
		}

		// Handle event file upload (check if a new file is being uploaded).
		if ( ! empty( $_FILES['event_file']['name'] ) ) {
			// Delete the existing event file if a new one is uploaded.
			if ( $existing_event->event_file && file_exists( $upload_path . '/' . $existing_event->event_file ) ) {
				$file = $upload_path . '/' . $existing_event->event_file;
				wp_delete_file( $file );
			}

			// Upload the new file.
			$event_file = self::handle_file_upload( 'event_file' );
			if ( is_wp_error( $event_file ) ) {
				return $this->response( $event_file->get_error_message(), 400 );
			}
		} else {
			$event_file = $existing_event->event_file;
		}

		// Handle placeholder upload (if the file type is video).
		if ( 'video' === $event_file_type ) {
			if ( ! empty( $_FILES['place_holder']['name'] ) ) {
				// Delete the existing placeholder file if a new one is uploaded.
				if ( $existing_event->place_holder && file_exists( $upload_path . '/' . $existing_event->place_holder ) ) {
					$file = $upload_path . '/' . $existing_event->place_holder;
					wp_delete_file( $file );
				}

				// Upload the new placeholder image.
				$place_holder = $this->handle_file_upload( 'place_holder' );
				if ( is_wp_error( $place_holder ) ) {
					// If this is a new event file, clean it up on error.
					if ( $event_file !== $existing_event->event_file ) {
						$this->remove_uploaded_file( $event_file );
					}
					return $this->response( $place_holder->get_error_message(), 400 );
				}
			} else {
				$place_holder = $existing_event->place_holder;
			}
		}

		// Prepare updated data.
		$data = array(
			'event_name'      => $event_name,
			'design_name'     => $design_name,
			'event_file'      => $event_file,
			'event_file_type' => $event_file_type,
			'place_holder'    => $place_holder,
		);

		// Update the event record in the database.
		$result = $gift_event->update( $data, $id );

		if ( $result ) {
			return $this->response( 'Event design updated successfully', 200 );
		} else {
			// If update fails and we've uploaded new files, clean them up.
			if ( $event_file !== $existing_event->event_file ) {
				$this->remove_uploaded_file( $event_file );
			}
			if ( ! empty( $place_holder ) && $place_holder !== $existing_event->place_holder ) {
				$this->remove_uploaded_file( $place_holder );
			}
			return $this->response( 'Failed to update event design', 500 );
		}
	}

	/**
	 * Delete event design
	 *
	 * Removes an event design and its associated files.
	 *
	 * @since 1.0.0
	 * @return \WP_REST_Response Response data.
	 */
	public function delete_event() {
		// Verify user capabilities.
		if ( ! current_user_can( 'manage_options' ) ) {
			return $this->response( 'Permission denied', 403 );
		}

		$id         = absint( $this->request->get( 'id' ) );
		$gift_event = GiftEvent::getInstance();
		
		// Fetch the existing record from the database.
		$existing_event = $gift_event->find( $id );

		if ( ! $existing_event ) {
			return $this->response( 'Event not found', 404 );
		}

		// Get the WordPress upload directory.
		$upload_dir  = wp_upload_dir();
		$upload_path = $upload_dir['basedir'] . '/' . SMART_GIFT_CARD_PLUGIN_ASSET_ID;

		// Delete the existing event file.
		if ( $existing_event->event_file && file_exists( $upload_path . '/' . $existing_event->event_file ) ) {
			$file = $upload_path . '/' . $existing_event->event_file;
			wp_delete_file( $file );
		}

		// Delete placeholder file if it's a video event.
		if ( 'video' === $existing_event->event_file_type && 
			 $existing_event->place_holder && 
			 file_exists( $upload_path . '/' . $existing_event->place_holder ) ) {
			$file = $upload_path . '/' . $existing_event->place_holder;
			wp_delete_file( $file );
		}

		$delete = $gift_event->destroy( $id );

		if ( $delete ) {
			return $this->response( 'Event design deleted successfully', 200 );
		} else {
			return $this->response( 'Failed to delete event design', 500 );
		}
	}

	/**
	 * Helper method to remove uploaded file
	 *
	 * @since 1.0.0
	 * @param string $file_name The name of the file to remove.
	 * @return bool True on success, false otherwise.
	 */
	private function remove_uploaded_file( $file_name ) {
		if ( empty( $file_name ) ) {
			return false;
		}

		$upload_dir  = wp_upload_dir();
		$upload_path = $upload_dir['basedir'] . '/' . SMART_GIFT_CARD_PLUGIN_ASSET_ID;
		$file_path   = $upload_path . '/' . $file_name;
		
		if ( file_exists( $file_path ) ) {
			return wp_delete_file( $file_path );
		}
		
		return false;
	}
}
