<?php
namespace Flyerimage\Controller;

use Throwable;
use WP_REST_Server;
use WP_REST_Controller;
use \WeDevs\ORM\Eloquent\Database;
use Flyerimage\App\Services\I18nService;
use Flyerimage\App\Services\FlyerImageService;
use Flyerimage\App\Exceptions\ServiceException;
use Flyerimage\App\Services\FlyerReportService;

/**
 * Home controller class
 */
class HomeController extends WP_REST_Controller
{
    protected $db;

    /**
     *
     * @var FlyerImageService $flyerImageService
     */
    protected $flyerImageService;
    protected $flyerReportService;
    protected $i18nService;

    /**
     * Initialize the class
     */
    public function __construct()
    {
        $this->namespace = 'flyer_image_v9622105412/v1';
        $this->db = Database::instance();
        $this->flyerImageService = new FlyerImageService();
    }

    /**
     * Register all routes for this controller
     * 
     * @return void
     */
    public function regiester_routes()
    {
        register_rest_route($this->namespace, '/load_elements', array(
            'methods'   => WP_REST_Server::READABLE,
            'callback'  => [$this, 'load_elements'],
            'permission_callback' => [$this, 'get_items_permissions_check'],
        ));
        register_rest_route($this->namespace, '/fis/list_flyers', array(
            'methods'   => WP_REST_Server::READABLE,
            'callback'  => [$this, 'list_flyers'],
            'permission_callback' => [$this, 'get_items_permissions_check'],
        ));
        register_rest_route($this->namespace, '/fis/create_configuration', array(
            'methods'   => WP_REST_Server::READABLE,
            'callback'  => [$this, 'create_configuration'],
            'permission_callback' => [$this, 'get_items_permissions_check'],
        ));
        register_rest_route($this->namespace, '/fis/list_posts', array(
            'methods'   => WP_REST_Server::READABLE,
            'callback'  => [$this, 'list_posts'],
            'permission_callback' => [$this, 'get_items_permissions_check'],
        ));
        register_rest_route($this->namespace, '/fis/list_post_categories', array(
            'methods'   => WP_REST_Server::READABLE,
            'callback'  => [$this, 'list_post_categories'],
            'permission_callback' => [$this, 'get_items_permissions_check'],
        ));
        register_rest_route($this->namespace, '/fis/save_flyer', array(
            'methods'   => WP_REST_Server::CREATABLE,
            'callback'  => [$this, 'save_flyer'],
            'permission_callback' => [$this, 'get_items_permissions_check'],
        ));
        register_rest_route($this->namespace, '/fis/save_flyer_image_copy', array(
            'methods'   => WP_REST_Server::CREATABLE,
            'callback'  => [$this, 'save_flyer_image_copy'],
            'permission_callback' => [$this, 'get_items_permissions_check'],
        ));
        register_rest_route($this->namespace, '/fis/change_flyer_status', array(
            'methods'   => WP_REST_Server::READABLE,
            'callback'  => [$this, 'change_flyer_status'],
            'permission_callback' => [$this, 'get_items_permissions_check'],
        ));
        register_rest_route($this->namespace, '/fis/get_flyer_for_preview', array(
            'methods'   => WP_REST_Server::READABLE,
            'callback'  => [$this, 'get_flyer_for_preview'],
            'permission_callback' => [$this, 'get_items_permissions_check'],
        ));
        register_rest_route($this->namespace, '/get-flyer', array(
            'methods'   => WP_REST_Server::READABLE,
            'callback'  => [$this, 'get_flyer'],
            'permission_callback' => '__return_true'
        ));
        register_rest_route($this->namespace, '/fis/register-flyer-report', array(
            'methods'   => WP_REST_Server::CREATABLE,
            'callback'  => [$this, 'register_flyer_report'],
            'permission_callback' => '__return_true'
        ));


        register_rest_route($this->namespace, '/fis/generate_flyer_report', array(
            'methods'   => WP_REST_Server::READABLE,
            'callback'  => [$this, 'generate_flyer_report'],
            'permission_callback' => [$this, 'get_items_permissions_check'],
        ));

        register_rest_route($this->namespace, '/fis/submit_form', array(
            'methods'             => WP_REST_Server::CREATABLE,
            'callback'            => [$this, 'submit_form'],
            'permission_callback' => '__return_true',
        ));

        register_rest_route($this->namespace, '/fis/get_submissions', array(
            'methods'             => WP_REST_Server::READABLE,
            'callback'            => [$this, 'get_submissions'],
            'permission_callback' => [$this, 'get_items_permissions_check'],
        ));
    }

    /**
     * Checks if a given request has access to read contacts
     * 
     * @param \WP_REST_Request $request
     * 
     * @return boolean
     */
    public function get_items_permissions_check($request)
    {
        if (current_user_can('manage_options')) {
            return true;
        }
        return false;
    }

    public function load_elements() {
        try {
            /*if ( ! is_admin() && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) {
                return rest_ensure_response([
                    'success' => false,
                    'error' => __('You are not authorized', 'flyerimage')
                ]);
            }*/
            $this->i18nService = new I18nService();
            $this->i18nService->registerParams();
            if ($this->i18nService->getParamString("check_build_file", "") == 1) {
                $file = FLYER_IMAGE_PUBLIC_PATH.DIRECTORY_SEPARATOR."flyer-image-web".DIRECTORY_SEPARATOR."main.js";
                return rest_ensure_response([
                    'success' => true,
                    'data' => [
                        "file_time" => file_exists($file) ? filemtime($file) : 0
                    ]
                ]);
            }
            (new \Flyerimage\Core\Init\Installer())->run();
            $data =  [
                'success' => true,
                'data' => $this->i18nService->load_elements()
            ];
            return rest_ensure_response($data);
        }
        catch (ServiceException $exception) {
            return rest_ensure_response([
                'success' => false,
                'error' => esc_html($exception->getMessage())
            ]);
        }
        catch (Throwable $exception) {
            return rest_ensure_response([
                'success' => false,
                'error' => esc_html__('Internal server error', 'flyerimage')
            ]);
        }
    }

    public function list_flyers($request)
    {
        
        try {
            $this->flyerImageService->registerParams();
            $data =  [
                'success' => true,
                'data' => $this->flyerImageService->list_flyers()
            ];
            return rest_ensure_response($data);
        }
        catch (ServiceException $exception) {
            return rest_ensure_response([
                'success' => false,
                'error' => esc_html($exception->getMessage())
            ]);
        }
        catch (Throwable $exception) {
            return rest_ensure_response([
                'success' => false,
                'error' => esc_html__('Internal server error', 'flyerimage')
            ]);
        }
    }

    public function create_configuration() {
        try {
            $this->flyerImageService->registerParams();
            $data =  [
                'success' => true,
                'data' => $this->flyerImageService->create_configuration()
            ];
            return rest_ensure_response($data);
        }
        catch (ServiceException $exception) {
            return rest_ensure_response([
                'success' => false,
                'error' => esc_html($exception->getMessage())
            ]);
        }
        catch (Throwable $exception) {
            return rest_ensure_response([
                'success' => false,
                'error' => esc_html__('Internal server error', 'flyerimage')
            ]);
        }
    }

    public function list_posts() {
        try {
            $this->flyerImageService->registerParams();
            return rest_ensure_response([
                'success' => false,
                'data' => $this->flyerImageService->list_internal_pages()
            ]);
        }
        catch (ServiceException $exception) {
            return rest_ensure_response([
                'success' => false,
                'error' => esc_html($exception->getMessage())
            ]);
        }
        catch (Throwable $exception) {
            return rest_ensure_response([
                'success' => false,
                'error' => esc_html__('Internal server error', 'flyerimage')
            ]);
        }
    }

    public function list_post_categories() {
        try {
            $this->flyerImageService->registerParams();
            return rest_ensure_response([
                'success' => false,
                'data' => $this->flyerImageService->list_post_categories()
            ]);
        }
        catch (ServiceException $exception) {
            return rest_ensure_response([
                'success' => false,
                'error' => esc_html($exception->getMessage())
            ]);
        }
        catch (Throwable $exception) {
            return rest_ensure_response([
                'success' => false,
                'error' => esc_html__('Internal server error', 'flyerimage')
            ]);
        }
    }

    public function save_flyer($request) {
        try {
            $this->flyerImageService->registerParams();
            $data =  [
                'success' => true,
                'data' => $this->flyerImageService->save_flyer()
            ];
            return rest_ensure_response($data);
        }
        catch (ServiceException $exception) {
            return rest_ensure_response([
                'success' => false,
                'error' => esc_html($exception->getMessage())
            ]);
        }
        catch (Throwable $exception) {
            return rest_ensure_response([
                'success' => false,
                'error' => esc_html__('Failed to create Campaign', 'flyerimage')
            ]);
        }
    }

    public function save_flyer_image_copy($request) {
        try {
            $this->flyerImageService->registerParams();
            $data =  [
                'success' => true,
                'data' => $this->flyerImageService->save_flyer_image_copy()
            ];
            return rest_ensure_response($data);
        }
        catch (ServiceException $exception) {
            return rest_ensure_response([
                'success' => false,
                'error' => esc_html($exception->getMessage())
            ]);
        }
        catch (Throwable $exception) {
            return rest_ensure_response([
                'success' => false,
                'error' => esc_html__('Failed to save Campaign image', 'flyerimage')
            ]);
        }
    }

    public function change_flyer_status($request) {
        try {
            $this->flyerImageService->registerParams();
            $data =  [
                'success' => true,
                'data' => $this->flyerImageService->change_flyer_status()
            ];
            return rest_ensure_response($data);
        }
        catch (ServiceException $exception) {
            return rest_ensure_response([
                'success' => false,
                'error' => esc_html($exception->getMessage())
            ]);
        }
        catch (Throwable $exception) {
            return rest_ensure_response([
                'success' => false,
                'error' => esc_html__('Failed to delete Campaign image', 'flyerimage')
            ]);
        }
    }

    public function get_flyer_for_preview($request) {
        try {
            $this->flyerImageService->registerParams();
            $data =  [
                'success' => true,
                'data' => $this->flyerImageService->get_flyer_for_preview()
            ];
            return rest_ensure_response($data);
        }
        catch (ServiceException $exception) {
            return rest_ensure_response([
                'success' => false,
                'error' => esc_html($exception->getMessage())
            ]);
        }
        catch (Throwable $exception) {
            return rest_ensure_response([
                'success' => false,
                'error' => esc_html__('Failed to get Campaign image', 'flyerimage')
            ]);
        }
    }

    public function get_flyer() {
        try {
            // Prevent caching of this endpoint to ensure fresh campaign data
            // This is critical because campaigns can change on a schedule
            header('Cache-Control: no-cache, no-store, must-revalidate, max-age=0');
            header('Pragma: no-cache');
            header('Expires: 0');
            
            // For WP Super Cache, W3 Total Cache, LiteSpeed, etc.
            // This prevents the response from being cached
            nocache_headers();
            
            $this->flyerImageService->registerParams();
            $data =  [
                'success' => true,
                'data' => $this->flyerImageService->get_flyer_for_main_page_display()
            ];
            
            $response = rest_ensure_response($data);
            
            // Also set cache headers on the response object
            $response->header('Cache-Control', 'no-cache, no-store, must-revalidate, max-age=0');
            $response->header('Pragma', 'no-cache');
            $response->header('Expires', '0');
            
            return $response;
        }
        catch (ServiceException $exception) {
            // Even error responses should not be cached
            nocache_headers();
            return rest_ensure_response([
                'success' => false,
                'error' => esc_html($exception->getMessage())
            ]);
        }
        catch (Throwable $exception) {
            nocache_headers();
            return rest_ensure_response([
                'success' => false,
                //'error' => esc_html__('Failed to get Flyer image', 'flyerimage')
                'error' => esc_html($exception->getMessage())
            ]);
        }
    }

    public function generate_flyer_report() {
        try {
            $this->flyerReportService = new FlyerReportService();
            $this->flyerReportService->registerParams();
            $data =  [
                'success' => true,
                'data' => $this->flyerReportService->route_to_respective_report_functionality()
            ];
            return rest_ensure_response($data);
        }
        catch (ServiceException $exception) {
            return rest_ensure_response([
                'success' => false,
                'error' => esc_html($exception->getMessage())
            ]);
        }
        catch (Throwable $exception) {
            return rest_ensure_response([
                'success' => false,
                'error' => esc_html__('Failed to generate report data', 'flyerimage'),
                'exception' => esc_html($exception->getMessage())
            ]);
        }
    }

    public function submit_form() {
        try {
            $this->flyerImageService->registerParams(true); // skip nonce — public frontend endpoint
            return rest_ensure_response([
                'success' => true,
                'data' => $this->flyerImageService->submit_form()
            ]);
        }
        catch (ServiceException $exception) {
            return rest_ensure_response(['success' => false, 'error' => esc_html($exception->getMessage())]);
        }
        catch (Throwable $exception) {
            return rest_ensure_response([
                'success' => false,
                'error'   => esc_html__('Submission failed', 'flyerimage'),
                'debug'   => esc_html($exception->getMessage()),
            ]);
        }
    }

    public function get_submissions() {
        try {
            $this->flyerImageService->registerParams();
            return rest_ensure_response([
                'success' => true,
                'data' => $this->flyerImageService->get_submissions()
            ]);
        }
        catch (ServiceException $exception) {
            return rest_ensure_response(['success' => false, 'error' => esc_html($exception->getMessage())]);
        }
        catch (Throwable $exception) {
            return rest_ensure_response(['success' => false, 'error' => esc_html__('Failed to load submissions', 'flyerimage')]);
        }
    }

    public function get_item_schema()
    {
        if ($this->schema) {
            return $this->add_additional_fields_schema($this->schema);
        }

        $schema = [
            '$schema'    => 'http://json-schema.org/draft-84/schema',
            'title'      => 'contact',
            'type'       => 'object',
            'properties' => []
        ];
        return $schema;
    }

    public function register_flyer_report() {
        try {
            // Prevent caching of reporting endpoint
            // Ensures accurate tracking data regardless of page cache status
            nocache_headers();
            
            // Skip nonce check for public tracking endpoint
            $this->flyerImageService->registerParams(true);
            $data =  [
                'success' => true,
                'data' => $this->flyerImageService->register_flyer_report()
            ];
            
            $response = rest_ensure_response($data);
            $response->header('Cache-Control', 'no-cache, no-store, must-revalidate, max-age=0');
            
            return $response;
        }
        catch (Throwable $exception) {
            nocache_headers();
            return rest_ensure_response([
                'success' => false,
                'error' => esc_html__('Unable to register report data', 'flyerimage'),
                'exception' => esc_html($exception->getMessage())
            ]);
        }
    }
}