<?php

namespace App\PackagesAdmin\User\Services;

use App\Packages\User\Models\User;
use Carbon\Carbon;

class UserExportService {

    public static function csvExport()
    {
        ini_set('max_execution_time', 180);

        $users = User::query()
            ->select([
                'table_user.*',
                'avatar.aws_key as avatar_key',
                \DB::raw("(SELECT COUNT(*) FROM table_follower_relation as followers 
                WHERE followers.user_id = table_user.id AND followers.status = true) as count_followers"),
                \DB::raw("(SELECT COUNT(*) FROM table_follower_relation as following 
                WHERE following.follower_id = table_user.id AND following.status = true) as count_following"),
                'total_capsule.total as count_capsules',
            ])
            ->leftJoin('table_user_avatar as avatar', 'avatar.id', '=', 'table_user.avatar_id')
            ->leftJoin(
                \DB::raw('(SELECT COUNT(*) as total, user_id FROM table_capsule WHERE is_complete = true GROUP BY user_id) as total_capsule'),
                'total_capsule.user_id',
                '=',
                'table_user.id'
            )
            ->orderBy('table_user.id', 'DESC')
            ->get();

        $now = new Carbon('now');
        $file_name = 'users_'.$now->format('d_m_y').'.csv';

        $headers = [
            "Content-type" => "text/csv",
            "Content-Disposition" => "attachment; filename={$file_name}",
            "Pragma" => "no-cache",
            "Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
            "Expires" => "0"
        ];

        $columns = [
            'ID',
            'UUID',
            'First Name',
            'Last Name',
            'Email',
            'Phone Code',
            'Phone Number',
            'Nickname',
            'Avatar',

            'Is Registered',
            'Is Notification push',
            'Is Notification app',
            'Is Suggested',
            'Is Private',

            'Count capsules',
            'Count comments',
            'Count Subscriptions',
            'Count followers',
            'Count following',

            'Created at',
            'Updated at',
            'Last notification seen',
            'Last follower seen',
            'Last follower confirmation seen',

            'Suggested position',
            'Search position',

            'IOS push token',
            'Facebook ID',
            'Google ID',
        ];

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

            foreach ($users as $user) {

                fputcsv($file, [
                    $user->id,
                    $user->uuid,
                    $user->first_name,
                    $user->last_name,
                    $user->email,
                    $user->phone_code,
                    $user->phone_number,
                    $user->nickname,
                    $user->avatar_key,

                    ($user->is_registered) ? 'True' : 'False',
                    ($user->is_notification_push) ? 'True' : 'False',
                    ($user->is_notification_app) ? 'True' : 'False',
                    ($user->is_suggested) ? 'True' : 'False',
                    ($user->is_private) ? 'True' : 'False',

                    ($user->count_capsules)?: 0,
                    $user->count_comments,
                    $user->count_subscriptions,
                    $user->count_followers,
                    $user->count_following,

                    ($user->created_at) ? $user->created_at->format('Y-m-d H:i:s') : '',
                    ($user->updated_at) ? $user->updated_at->format('Y-m-d H:i:s') : '',
                    $user->last_notification_seen, // Here
                    ($user->last_follower_seen) ? $user->last_follower_seen->format('Y-m-d H:i:s') : '',
                    ($user->last_follower_confirmation_seen) ? $user->last_follower_confirmation_seen->format('Y-m-d H:i:s') : '',

                    $user->suggested_position,
                    $user->search_position,

                    $user->ios_push_token,
                    $user->fb_id,
                    $user->google_id
                ]);
            }

            fclose($file);
        };

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

    }

}