<?php
namespace Softech_Addons_for_Elementor\Widgets;
if ( ! defined( 'ABSPATH' ) ) exit;

use Elementor\Widget_Base;
use Elementor\Controls_Manager;

class sitsel_pdf_viewer extends Widget_Base {

    public function get_name() {
        return 'sitsel_pdf_viewer';
    }

    public function get_title() {
        return __( 'SITS PDF Viewer', 'softech-addons-for-elementor' );
    }

    public function get_icon() {
        return 'eicon-document-file';
    }

    public function get_categories() {
        return [ 'sits-category' ];
    }

    protected function register_controls() {

        $this->start_controls_section(
            'content_section',
            [
                'label' => __( 'PDF Settings', 'softech-addons-for-elementor' ),
                'tab'   => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'pdf_file',
            [
                'label'   => __( 'Upload PDF', 'softech-addons-for-elementor' ),
                'type'    => Controls_Manager::MEDIA,
                'media_types' => ['application/pdf'],
                'default' => [],
            ]
        );

        $this->add_control(
            'pdf_height',
            [
                'label' => __( 'Height (px)', 'softech-addons-for-elementor' ),
                'type' => Controls_Manager::NUMBER,
                'default' => 600,
            ]
        );

        $this->end_controls_section();
    }

protected function render() {
    $settings = $this->get_settings_for_display();

    if ( ! empty( $settings['pdf_file']['url'] ) ) {
        $pdf_url = esc_url( $settings['pdf_file']['url'] );
       $filetype = wp_check_filetype( $pdf_url );
        if ( $filetype['type'] !== 'application/pdf' ) {
            echo esc_html__( 'The uploaded file is not a valid PDF.', 'softech-addons-for-elementor' );
            return;
        }
        if ( strpos( $pdf_url, '.pdf' ) === false && $filetype['type'] !== 'application/pdf' ) {
            echo esc_html__( 'Only direct PDF links are allowed.', 'softech-addons-for-elementor' );
            return;
        }

        $height = ! empty( $settings['pdf_height'] ) ? intval( $settings['pdf_height'] ) : 600;

        echo '<div class="sitsel-pdf-viewer">';
        printf(
            '<iframe src="%s" width="100%%" height="%d" style="border:none;" loading="lazy"></iframe>',
            esc_url( $pdf_url ),
            esc_attr( $height )
        );
        echo '</div>';

    } else {
        echo esc_html__( 'Please upload a PDF file.', 'softech-addons-for-elementor' );
    }
}
}
