<?php
/**
 * SocialPilot API Handler
 *
 * @package SocialPilot
 * @subpackage API
 * @since 1.0.0
 */

/**
 * Class to handle all API interactions with SocialPilot
 */
class SocialPilot_API {

    /**
     * Instance of this class
     *
     * @since 1.0.0
     * @var object
     */
    private static $instance = null;

    /**
     * API key for SocialPilot
     *
     * @since 1.0.0
     * @var string
     */
    private $api_key = '';

    /**
     * Base URL for API endpoints
     *
     * @since 1.0.0
     * @var string
     */
    private $api_base_url = 'https://api.socialpilot.co/v1/';

    /**
     * Get singleton instance
     *
     * @since 1.0.0
     * @return SocialPilot_API
     */
    public static function get_instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor
     *
     * @since 1.0.0
     */
    private function __construct() {
        $options = get_option( 'socialpilot_options', array() );
        $this->api_key = isset( $options['api_key'] ) ? 
            SocialPilot_Encrypt::decrypt( $options['api_key'] ) : '';
    }

    /**
     * Make API request
     *
     * @since 1.0.0
     * @param string $endpoint API endpoint.
     * @param string $method HTTP method.
     * @param array  $data Request data.
     * @return array Response data
     * @throws Exception If request fails.
     */
    private function make_request( $endpoint, $method = 'GET', $data = null ) {
        $url = $this->api_base_url . ltrim( $endpoint, '/' );
        
        $args = array(
            'method'  => $method,
            'headers' => array(
                'x-api-key'    => $this->api_key,
                'Content-Type' => 'application/json',
                'Accept'       => 'application/json',
            ),
            'timeout' => 30,
        );

        if ( $data !== null ) {
            $args['body'] = wp_json_encode( $data );
        }

        $response = wp_remote_request( $url, $args );
        
        if ( is_wp_error( $response ) ) {
            throw new Exception( $response->get_error_message() );
        }

        $body = wp_remote_retrieve_body( $response );
        $status = wp_remote_retrieve_response_code( $response );
        $decoded_body = json_decode( $body, true );

        if ( $status !== 200 ) {

            $error_message = isset( $decoded_body['message'] ) ? 
                $decoded_body['message'] : __( 'Unknown API error', 'socialpilot-wp' );

        
            if(isset($decoded_body['reasons']) && isset($decoded_body['reasons'][0])){
                $error_message = $decoded_body['reasons'][0]['message'];
            }
           
            throw new Exception( $error_message );
        }

        return $decoded_body;
    }

    /**
     * Get social media accounts
     *
     * @since 1.0.0
     * @return array Account list
     * @throws Exception If request fails.
     */
    public function get_accounts() {
        return $this->make_request( 'accounts/list?ignoreAccountIds=26' );
    }

    /**
     * Upload media to SocialPilot
     *
     * @since 1.0.0
     * @param string $media_url URL of the media to upload.
     * @param string $media_type Type of media (IMAGE, VIDEO).
     * @return array Upload response
     * @throws Exception If request fails.
     */
    public function upload_media( $media_url, $media_type ) {
        $data = array(
            'mediaType' => strtoupper( $media_type ),
            'media'     => array(
                array( 'url' => $media_url ),
            ),
        );

        return $this->make_request( 'uploadmedia', 'POST', $data );
    }

    /**
     * Schedule a post
     *
     * @since 1.0.0
     * @param array $post_data Post data to schedule.
     * @return array Schedule response
     * @throws Exception If request fails or validation fails.
     */
    public function schedule_post( $post_data ) {
        $this->validate_post_data( $post_data );
        return $this->make_request( 'posts/create', 'POST', $post_data );
    }

    /**
     * Generate caption using AI
     *
     * @since 1.0.0
     * @param string $title Post title.
     * @param string $content Post content.
     * @return array Generated caption
     * @throws Exception If request fails.
     */
    public function generate_caption( $title, $content ) {
        $data = array(
            'selectedText' => $title . "\n\n" . $content,
            'caseType'    => 'o-editor-full-generatePost',
        );

        return $this->make_request( 'openai/generatecaption', 'POST', $data );
    }
    

    /**
     * Validate schedule time
     *
     * @since 1.0.0
     * @param string $schedule_time Schedule time in Y-m-d H:i:s format.
     * @return bool True if valid
     * @throws Exception If validation fails.
     */
    private function validate_schedule_time( $schedule_time ) {
        $schedule_timestamp = strtotime( $schedule_time );
        $current_timestamp = current_time( 'timestamp' );

        if ( $schedule_timestamp < $current_timestamp ) {
            throw new Exception( 
                __( 'Schedule time must be in the future', 'socialpilot-wp' )
            );
        }

        // Ensure minimum 30 minutes buffer
        if ( $schedule_timestamp < ( $current_timestamp + ( 30 * MINUTE_IN_SECONDS ) ) ) {
            throw new Exception( 
                __( 'Schedule time must be at least 30 minutes from now', 'socialpilot-wp' )
            );
        }

        return true;
    }

    /**
     * Validate post data
     *
     * @since 1.0.0
     * @param array $data Post data to validate.
     * @return bool True if valid
     * @throws Exception If validation fails.
     */
    private function validate_post_data( $data ) {
        if ( empty( $data['posts'][0]['postDesc'] ) ) {
            throw new Exception( 
                __( 'Post caption is required', 'socialpilot-wp' )
            );
        }

        if ( empty( $data['loginIds'] ) || ! is_array( $data['loginIds'] ) ) {
            throw new Exception( 
                __( 'At least one social media account must be selected', 'socialpilot-wp' )
            );
        }

        if ( empty( $data['scheduleDateTime'] ) || ! is_array( $data['scheduleDateTime'] ) ) {
            throw new Exception( 
                __( 'Schedule time is required', 'socialpilot-wp' )
            );
        }

        foreach ( $data['scheduleDateTime'] as $time ) {
            $this->validate_schedule_time( $time );
        }

        return true;
    }
}