<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CampaignReportController extends Controller
{
    public function reports(Request $request)
    {
        if ($request->from_date ) {
            $from_date = $request->from_date;
        } else {
            $from_date = new Carbon('first day of this month');
        }

        if ($request->to_date) {
            $to_date = $request->to_date;
        } else {
            $to_date = new Carbon('last day of this month');
        }

        if ($request->state) {
            $state = $request->state;
            $data['title'] = ($request->state === 'rejected')?'Rejected Mail List':'Sent Mail List';
        } else {
            $state = 'sent';            
        }        

        $from_date = date('Y-m-d', strtotime($from_date));
        $to_date = date('Y-m-d', strtotime($to_date));
        
        if (isAdmin()) {
            $senders = $this->sendersArray();

        } else {
            $senders = [Auth::user()->email];
        }

        $url = "https://mandrillapp.com/api/1.0/messages/search.json";

        $options = array(
                    CURLOPT_RETURNTRANSFER => true, // return web page
                    CURLOPT_HEADER         => false,// don't return headers
                    CURLOPT_FOLLOWLOCATION => false,// follow redirects
                    // CURLOPT_ENCODING       => "utf-8",  // handle all encodings
                    CURLOPT_AUTOREFERER    => true,  // set referer on redirect
                    CURLOPT_CONNECTTIMEOUT => 20, // timeout on connect
                    CURLOPT_TIMEOUT        => 1220, // timeout on response
                    CURLOPT_POST            => 1, // i am sending post data
                    CURLOPT_POSTFIELDS     => json_encode([
                        'key'=>env('MANDRILL_SECRET', 'NaZxQF7HNH-aRPpJzGxd6A'),
                        'api_key'=>env('MANDRILL_SECRET', 'NaZxQF7HNH-aRPpJzGxd6A'), 
                        'query'=>'state:'.$state, 
                        'date_from'=> $from_date,
                        'date_to'=> $to_date,
                        'tags'=>['welcome'], 
                        'senders'=>$senders
                    ]),    // this are my post vars
                    CURLOPT_SSL_VERIFYHOST => 0, // don't verify ssl
                    CURLOPT_SSL_VERIFYPEER => false,
                    CURLOPT_VERBOSE        => 1,
                    CURLOPT_HTTPHEADER     => array(
                        "Content-Type: application/json"
                    )
                );

        $list = callCrl($url, $options);
        $data['list'] = json_decode($list);

        return view('mail-campaign.reports.email-list-view', $data);
    }
}
