<?php

/**
 * Campaign Controller
 *
 * This file is used to register all actions for the Campaign Controller.
 *
 * @since 1.0.0
 */

namespace LinkFiliate\App\Controllers;

if (! defined('ABSPATH')) {
    exit;
}

use LinkFiliate\App\Models\Campaigns as CampaignModel;
use LinkFiliate\App\Models\Setting;

class Campaign
{

    /**
     * Get all campaigns.
     */
    public function get_all(\WP_REST_Request $request)
    {
        $datefrom = $request->get_param('from') ? sanitize_text_field($request->get_param('from')) : '';
        $dateend  = $request->get_param('to') ? sanitize_text_field($request->get_param('to')) : '';

        if (empty($datefrom) || empty($dateend)) {
            return new \WP_REST_Response([
                'status' => 'error',
                'message' => 'Parameter required.'
            ], 400);
        }

        $from = $datefrom . ' 00:00:00';
        $to   = $dateend . ' 23:59:59';

        $diffDays = (strtotime($to) - strtotime($from)) / (60 * 60 * 24);

        if ($diffDays > 14) {
            return new \WP_REST_Response([
                'status'  => 'error',
                'message' => 'Free accounts are limited to 14-day reports. Please upgrade to unlock full range.'
            ], 403);
        }

        $campaign = new CampaignModel();

        $result = $campaign->get_all();

        if (!$result) {
            return new \WP_REST_Response([
                'status' => 'error',
                'message' => 'Campaign not found'
            ], 404);
        }
        $campaignData = array();

        $settingModel = new Setting();
        $generalSettings = $settingModel->get_general();

        $customPrefix = $generalSettings['customPrefix'] ?? '';
        $disablePrefixByDefault = $generalSettings['disablePrefixByDefault'] ?? false;

        foreach ($result as $mktArr) {
            $mkt = json_decode(json_encode($mktArr));

            // Determine final slug logic
            $finalSlug = $mkt->slug;

            // If prefix is enabled globally
            if (! $disablePrefixByDefault && $customPrefix) {
                $finalSlug = trailingslashit($customPrefix) . $finalSlug;
            }

            $rowData = [
                'id' => $mkt->id,
                'name' => $mkt->name,
                'category_id' => $mkt->category_id,
                'category_name' => $mkt->category_name,
                'slug' => $finalSlug,
                'target_url' =>$mkt->target_url,
                'total_clicks' => intval($mkt->total_clicks),
                'status' => $mkt->status,
                'created_at' => $mkt->created_at,
                'updated_at' => $mkt->updated_at,
            ];

            $campaignData[] = $rowData;
        }


        return new \WP_REST_Response([
            'status' => 'success',
            'data' => $campaignData
        ], 200);
    }


    /**
     * Get campaigns by keyword from Gutenberg.
     */
    public function search_link($request)
    {
        $keyword = sanitize_text_field($request->get_param('s')); // ambil query string ?s=

        $campaign = new CampaignModel();
        $settingModel = new Setting();

        $generalSettings = $settingModel->get_general();

        $customPrefix = $generalSettings['customPrefix'] ?? '';
        $disablePrefixByDefault = $generalSettings['disablePrefixByDefault'] ?? false;
        // Jika CampaignModel sudah punya fungsi search, gunakan
        if ($keyword) {
            $result = $campaign->search_by_name($keyword);
        } else {
            $result = $campaign->get_all();
        }

        if (!$result) {
            return new \WP_REST_Response([
                'status' => 'error',
                'message' => 'Campaign not found'
            ], 404);
        }

        $campaignData = array();

        foreach ($result as $mktArr) {
            $mkt = json_decode(json_encode($mktArr));

            $finalSlug = $mkt->slug;

            // If prefix is enabled globally
            if (! $disablePrefixByDefault && $customPrefix) {
                $finalSlug = trailingslashit($customPrefix) . $finalSlug;
            }
            $campaignData[] = array(
                'id' => $mkt->id,
                'name' => $mkt->name,
                'category_id' => $mkt->category_id,
                'category_name' => $mkt->category_name,
                'slug' => $finalSlug,
                'total_clicks' => intval($mkt->total_clicks),
                'status' => $mkt->status,
                'settings'      => json_decode($mkt->settings, true),
                'created_at' => $mkt->created_at,
                'updated_at' => $mkt->updated_at,
            );
        }

        return new \WP_REST_Response([
            'status' => 'success',
            'data' => $campaignData
        ], 200);
    }


    /**
     * Get campaign by id.
     */

    public function get_by(\WP_REST_Request $request)
    {
        $id = intval($request->get_param('id'));
        $campaign = new CampaignModel();
        $result = $campaign->find($id);

        if (!$result) {
            return new \WP_REST_Response([
                'status' => 'error',
                'message' => 'Campaign not found'
            ], 404);
        }

        // Decode JSON settings safely
        $settings = json_decode($result['settings'] ?? '{}', true);

        // Merge defaults (in case older rows have missing keys)
        $defaults = [
            'no_follow'             => 0,
            'sponsored'             => 0,
            'parameter_forwarding'  => 0,
            'tracking'              => 1,
        ];

        $settings = array_merge($defaults, $settings);

        // Prepare response
        $campaignData = [
            'id'             => intval($result['id'] ?? 0),
            'name'           => $result['name'] ?? '',
            'description'    => $result['description'] ?? '',
            'status'         => $result['status'] ?? '',
            'slug'           => $result['slug'] ?? '',
            'category_id' => $result['category_id'] ?? null,
            'redirect_type'  => $result['redirect_type'] ?? '',
            'target_url'     => $result['target_url'] ?? '',
            'settings'       => $settings, // return decoded array
            'created_at'     => $result['created_at'] ?? '',
            'updated_at'     => $result['updated_at'] ?? '',
        ];

        return new \WP_REST_Response([
            'status' => 'success',
            'data'   => $campaignData
        ], 200);
    }


    /**
     * Create Campaign Function.
     */
    public function create(\WP_REST_Request $request)
    {
        $data = $request->get_json_params();
        $campaign_name  = isset($data['campaign_name']) ? sanitize_text_field($data['campaign_name']) : '';
        $status         = isset($data['status']) ? sanitize_text_field($data['status']) : 'inactive';
        $category       = isset($data['category']) ? sanitize_text_field($data['category']) : '';
        $desc           = isset($data['desc']) ? sanitize_textarea_field($data['desc']) : '';
        $redirect_type  = isset($data['redirect_type']) ? sanitize_text_field($data['redirect_type']) : '302';
        $target_url     = isset($data['target_url']) ? esc_url_raw($data['target_url']) : '';
        $slug           = isset($data['slug']) ? sanitize_title($data['slug']) : '';
        $no_follow      = !empty($data['no_follow']) ? 1 : 0;
        $sponsored      = !empty($data['sponsored']) ? 1 : 0;
        $parameter_forwarding = !empty($data['parameter_forwarding']) ? 1 : 0;
        $tracking       = !empty($data['tracking']) ? 1 : 0;

        if (!$campaign_name) {
            return new \WP_REST_Response([
                'status' => 'error',
                'message' => 'Campaign name is required.'
            ], 400);
        }
        if (!$target_url) {
            return new \WP_REST_Response([
                'status' => 'error',
                'message' => 'Target URL is required.'
            ], 400);
        }
        if (!$redirect_type) {
            return new \WP_REST_Response([
                'status' => 'error',
                'message' => 'Redirect type is required.'
            ], 400);
        }
        $campaign = new CampaignModel();

        // Build settings array
        $settings = [
            'redirect_type'         => $redirect_type,
            'no_follow'             => (bool) $no_follow,
            'sponsored'             => (bool) $sponsored,
            'parameter_forwarding'  => (bool) $parameter_forwarding,
            'tracking'              => (bool) $tracking,
        ];
        $inserted = $campaign->create([
            'name'          => $campaign_name,
            'slug'          => $slug,
            'target_url'   => $target_url,
            'redirect_type' => $redirect_type,
            'description'   => $desc,
            'status'        => $status,
            'category_id'   => $category,
            'settings'      => json_encode($settings),
        ]);

        if (!$inserted) {
            return new \WP_REST_Response([
                'status' => 'error',
                'message' => 'Error saved campaign.'
            ], 500);
        }


        return new \WP_REST_Response([
            'status' => 'success',
            'message' => 'Campaign successfully craeted.',
            'data' => [
                'id' => $inserted
            ]
        ], 201);
    }


    /**
     * Create Campaign Function.
     */
    public function update_by(\WP_REST_Request $request)
    {
        $campaign_id     = intval($request->get_param('id'));
        $data = $request->get_json_params();
        $campaign_name  = isset($data['campaign_name']) ? sanitize_text_field($data['campaign_name']) : '';
        $status         = isset($data['status']) ? sanitize_text_field($data['status']) : 'inactive';
        $category       = isset($data['category']) ? sanitize_text_field($data['category']) : '';
        $desc           = isset($data['desc']) ? sanitize_textarea_field($data['desc']) : '';
        $redirect_type  = isset($data['redirect_type']) ? sanitize_text_field($data['redirect_type']) : '302';
        $target_url     = isset($data['target_url']) ? esc_url_raw($data['target_url']) : '';
        $slug           = isset($data['slug']) ? sanitize_title($data['slug']) : '';
        $no_follow      = !empty($data['no_follow']) ? 1 : 0;
        $sponsored      = !empty($data['sponsored']) ? 1 : 0;
        $parameter_forwarding = !empty($data['parameter_forwarding']) ? 1 : 0;
        $tracking       = !empty($data['tracking']) ? 1 : 0;

        if (!$campaign_id) {
            return new \WP_REST_Response([
                'status'  => 'error',
                'message' => 'Invalid campaign ID.'
            ], 400);
        }
        $settings = [
            'redirect_type'         => $redirect_type,
            'no_follow'             => (bool) $no_follow,
            'sponsored'             => (bool) $sponsored,
            'parameter_forwarding'  => (bool) $parameter_forwarding,
            'tracking'              => (bool) $tracking,
        ];

        $campaign = new CampaignModel();

        $updated = $campaign->update($campaign_id, [
            'name'   => $campaign_name,
            'slug'          => $slug,
            'target_url'   => $target_url,
            'redirect_type' => $redirect_type,
            'description'   => $desc,
            'status'        => $status,
            'category_id'   => $category,
            'settings'    => json_encode($settings),
            'updated_at' => current_time('mysql'),
        ]);


        if ($updated === false) {
            return new \WP_REST_Response([
                'status' => 'error',
                'message' => 'Failed to update Campaign'
            ], 500);
        }


        return new \WP_REST_Response([
            'status' => 'success',
            'message' => 'Campaign updated successfully'
        ], 200);
    }

    /**
     * Create Campaign Function.
     */
    public function delete_by(\WP_REST_Request $request)
    {

        $id     = intval($request->get_param('id'));
        $campaign = new CampaignModel();
        $deleted = $campaign->delete($id);

        if ($deleted === false) {
            return new \WP_REST_Response([
                'status' => 'error',
                'message' => 'Failed to delete Campaign'
            ], 500);
        }

        return new \WP_REST_Response([
            'status' => 'success',
            'message' => 'Campaign deleted successfully'
        ], 200);
    }

    public function check_slug(\WP_REST_Request $request)
    {

        $slug = sanitize_title($request->get_param('slug'));
        if (empty($slug)) {
            return new \WP_REST_Response([
                'success' => false,
                'message' => 'Slug is required.'
            ], 400);
        }

        $campaign = new CampaignModel();
        $exists = $campaign->find_by_slug($slug);

        return new \WP_REST_Response([
            'success' => true,
            'exists'  => !empty($exists),
            'slug'    => $slug
        ], 200);
    }
    /**
     * Get Targets Function.
     */
    public function get_targets(\WP_REST_Request $request)
    {
        $resultData = array();

        // Add homepage
        $resultData[] = array(
            'id' => 'home',
            'title' => 'Homepage',
            'url' => home_url('/'),
            'type' => 'special'
        );

        // Add "All Pages" option
        $resultData[] = array(
            'id' => 'all_pages',
            'title' => 'All Pages',
            'url' => '*',
            'type' => 'special'
        );

        // Add "All Posts" option
        $resultData[] = array(
            'id' => 'all_posts',
            'title' => 'All Posts',
            'url' => '*',
            'type' => 'special'
        );

        // Get all published pages
        $pages = get_pages(['post_status' => 'publish']);
        $pages_data = array();
        foreach ($pages as $page) {
            $pages_data[] = array(
                'id' => $page->ID,
                'title' => $page->post_title,
                'url' => get_permalink($page->ID),
                'type' => 'page',
                'parent' => 'specific_pages'
            );
        }

        // Get all published posts
        $posts = get_posts(['post_status' => 'publish', 'numberposts' => -1]);
        $posts_data = array();
        foreach ($posts as $post) {
            $posts_data[] = array(
                'id' => $post->ID,
                'title' => $post->post_title,
                'url' => get_permalink($post->ID),
                'type' => 'post',
                'parent' => 'specific_posts'
            );
        }

        // Add categories with their children
        if (!empty($pages_data)) {
            $resultData[] = array(
                'id' => 'specific_pages',
                'title' => 'Specific Pages',
                'type' => 'category',
                'children' => $pages_data
            );
        }

        if (!empty($posts_data)) {
            $resultData[] = array(
                'id' => 'specific_posts',
                'title' => 'Specific Posts',
                'type' => 'category',
                'children' => $posts_data
            );
        }

        return new \WP_REST_Response([
            'status' => 'success',
            'data' => $resultData
        ], 200);
    }
}
