<?php

namespace MtcPharmacy\Subscriptions\Http\Controllers\Admin;

use App\Support\PaginationPresenter;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Session;
use MtcPharmacy\Subscriptions\Classes\Subscription;
use MtcPharmacy\Subscriptions\Classes\SubscriptionLog;

class SubscriptionLogsController extends \App\Http\Controllers\Controller
{
    public function index(Request $request)
    {
        // Paging params
        $per_page = (int) $request->input('per_page', 50);
        if ($per_page < 1)   { $per_page = 50; }
        if ($per_page > 250) { $per_page = 250; }

        // Default date range
        if (!$request->has('date_start')) {
            $request->merge(['date_start' => Carbon::now()->subDays(30)->format('Y-m-d')]);
        }
        if (!$request->has('date_end')) {
            $request->merge(['date_end' => Carbon::now()->format('Y-m-d')]);
        }

        // Base query + filters
        $query = SubscriptionLog::query()
                                ->with(['subscription.member']); // eager-load to avoid N+1

        $query = $this->filterLogs($query, $request);

        // Paginate
        $logsPaginator = $query->orderBy('id', 'desc')
                               ->paginate($per_page)
                               ->appends($request->except('page')); // persist filters

        // Map for display, but keep paginator wrapper
        $mapped = $logsPaginator->getCollection()->map(function ($log) {
            return [
                'id' => $log->id,
                'subscription_id' => $log->subscription_id,
                'subscription_member' => $log->subscription ? $log->subscription->member->full_name : 'N/A',
                'action_type' => $log->action_type,
                'action_description' => $log->action_description,
                'actor' => $log->getActorName(),
                'source' => ucfirst($log->source),
                'changes' => $log->getChangesSummary(),
                'created_at' => $log->getFormattedDate(),
                'ip_address' => $log->ip_address,
                'actions' => [
                    'view' => route('admin-subscription-logs-view', $log->id),
                ],
            ];
        });

        // Replace paginator items with mapped rows
        $logsPaginator->setCollection($mapped);

        //  Build presenter for your Twig pagination partial
        $pagination = PaginationPresenter::fromPaginator(
            $logsPaginator,
            route('admin-subscription-logs'),
            $request->except('page'),
            10, // pagesToShow
            'page-link', // link class used in your Twig
            true, // show page numbers
            true, // show "Page X of Y"
            false, // show view-all button
        );

        //  Action counts (unchanged)
        $action_counts = [];
        foreach (SubscriptionLog::getActionTypes() as $action => $label) {
            $action_counts[$action] = SubscriptionLog::byActionType($action)->count();
        }

        //  Render template
        return template('admin/subscription_logs_index.twig', [
            'title'          => 'Subscription Logs',
            // You can iterate this paginator directly in Twig or use `.items`
            'logs'           => $logsPaginator,
            'action_types'   => SubscriptionLog::getActionTypes(),
            'sources'        => SubscriptionLog::getSources(),
            'action_counts'  => $action_counts,
            'pagination'     => $pagination,               // your existing Twig partial expects this object
            'request'        => $request->all(),
            'total'          => $logsPaginator->total(),   // replaces $totalnumrows
            'page_meta'      => ['title' => 'Subscription Logs'],
        ]);
    }

    public function view(int $log_id, Request $request)
    {
        $log = SubscriptionLog::with(['subscription', 'member'])->findOrFail($log_id);

        $recent_logs = SubscriptionLog::forSubscription($log->subscription_id)
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get();

        return template('admin/subscription_log_view.twig', [
            'title' => 'Subscription Log Details',
            'log' => $log,
            'recent_logs' => $recent_logs,
            'page_meta' => [
                'title' => 'Subscription Log #' . $log->id,
            ]
        ]);
    }

    public function forSubscription(int $subscription_id, Request $request)
    {
        $subscription = Subscription::findOrFail($subscription_id);


        // Get pagination parameters
        $pageNum = $request->input('page', 1);
        $per_page = $request->input('per_page', 25);
        if ($per_page > 100) {
            $per_page = 100;
        }
        $rowsPerPage = $per_page;

        $query = SubscriptionLog::forSubscription($subscription_id)
            ->with(['subscription', 'member']);

        // Get total count for pagination
        $totalnumrows = $query->count();

        // Calculate offset and get paginated results
        $offset = ($pageNum - 1) * $per_page;
        $logs = $query->orderBy('id', 'desc')
            ->skip($offset)
            ->take($per_page)
            ->get();

        $formatted_logs = $logs->map(function ($log) {
            return [
                'id' => $log->id,
                'subscription_id' => $log->subscription_id,
                'action_type' => $log->action_type,
                'action_description' => $log->action_description,
                'actor' => $log->getActorName(),
                'source' => ucfirst($log->source),
                'changes' => $log->getChangesSummary(),
                'created_at' => $log->getFormattedDate(),
                'ip_address' => $log->ip_address,
                'actions' => [
                    'view' => route('admin-subscription-logs-view', $log->id),
                ],
            ];
        });

        $self = route('admin-subscription-logs-for-subscription', $subscription_id);

        // Generate pagination HTML
        $pagestoshow = 10;
        $append = '';
        ob_start();
        include(base_path('core/admin/templates/pagination.php'));
        echo '<hr>';
        include(base_path('core/admin/templates/per_page.php'));
        echo '<hr>';

        $pagination = ob_get_clean();

        return template('admin/subscription_logs_for_subscription.twig', [
            'title' => 'Subscription #' . $subscription_id,
            'subscription' => $subscription,
            'logs' => $formatted_logs,
            'pagination' => $pagination,
            'total' => $totalnumrows,
            'page_meta' => [
                'title' => 'Subscription #' . $subscription_id,
            ]
        ]);
    }

    public function export(Request $request)
    {
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="subscription-logs-' . date('Y-m-d') . '-' . time() . '.csv"',
            'Pragma' => 'no-cache',
            'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
            'Expires' => '0'
        ];

        $query = SubscriptionLog::query()
            ->with(['subscription', 'member']);

        $query = $this->filterLogs($query, $request);

        $logs = $query->orderBy('created_at', 'desc')->cursor();

        $callback = function () use ($logs) {
            $file = fopen('php://output', 'w');

            // Add CSV headers
            fputcsv($file, [
                'Log ID',
                'Subscription ID',
                'Member Name',
                'Member Email',
                'Action Type',
                'Description',
                'Actor',
                'Source',
                'Changes',
                'IP Address',
                'Date/Time',
            ]);

            foreach ($logs as $log) {
                fputcsv($file, [
                    $log->id,
                    $log->subscription_id,
                    $log->subscription ? $log->subscription->member->full_name : 'N/A',
                    $log->subscription ? $log->subscription->member->email : 'N/A',
                    $log->action_type,
                    $log->action_description,
                    $log->getActorName(),
                    ucfirst($log->source),
                    $log->getChangesSummary() ?: 'No changes',
                    $log->ip_address ?: 'N/A',
                    $log->getFormattedDate(),
                ]);
            }

            fclose($file);
        };

        return response()->stream($callback, 200, $headers);
    }

    protected function filterLogs(Builder $query, Request $request)
    {
        if ($request->has('subscription_id') && !empty($request->input('subscription_id'))) {
            $query->where('subscription_id', $request->input('subscription_id'));
        }

        if ($request->has('action_type') && !empty($request->input('action_type'))) {
            $query->where('action_type', $request->input('action_type'));
        }

        if ($request->has('source') && !empty($request->input('source'))) {
            $query->where('source', $request->input('source'));
        }

        if ($request->has('member_id') && !empty($request->input('member_id'))) {
            $query->where('member_id', $request->input('member_id'));
        }

        if ($request->has('date_start') && !empty($request->input('date_start'))) {
            $query->whereDate('created_at', '>=', $request->input('date_start'));
        }

        if ($request->has('date_end') && !empty($request->input('date_end'))) {
            $query->whereDate('created_at', '<=', $request->input('date_end'));
        }

        return $query;
    }
}