<?php

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

namespace LinkFiliate\App\Controllers;

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

use LinkFiliate\App\Models\Campaigns;

class Overview
{
    public function get_chart(\WP_REST_Request $request)
    {
        global $wpdb;

        $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);
        }

        $clicks_table = $wpdb->prefix . LINKFILIATE_DB_BASE . '_clicks';


        $query = $wpdb->prepare(
            "SELECT created_at FROM %i
         WHERE created_at BETWEEN %s AND %s",
            $clicks_table,
            $from,
            $to
        );

        $results = $wpdb->get_results($query); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

        // count click per day
        $chartData = [];
        foreach ($results as $row) {
            $date = gmdate("Y-m-d", strtotime($row->created_at));
            if (!isset($chartData[$date])) {
                $chartData[$date] = 0;
            }
            $chartData[$date]++;
        }

        // Generate $datefrom to $dateend
        $period = new \DatePeriod(
            new \DateTime($datefrom),
            new \DateInterval('P1D'),
            (new \DateTime($dateend))->modify('+1 day')
        );

        $finalData = [];
        foreach ($period as $date) {
            $d = $date->format('Y-m-d');
            $count = isset($chartData[$d]) ? $chartData[$d] : 0;

            $finalData[] = [
                'name' => $date->format('d M Y'),
                'clicks' => $count
            ];
        }

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

    public function get_campaigns(\WP_REST_Request $request)
    {
        global $wpdb;

        $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);
        }


        $campaigns = new Campaigns();
        $results = $campaigns->get_top_campaigns($from, $to);

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