<?php

namespace App\Http\Controllers;

use App\Http\Requests;

use Illuminate\Http\Request;

use DB;

use Carbon\Carbon;

use Session;

use Hash;

use PDF;



class DisputeController extends Controller
{

    /**

     * Create a new controller instance.

     *

     * @return void

     */

    public function __construct()
    {

        parent::__construct($this->masterModel);

    }

    public function index()
    {
        $data['pending'] = $this->masterModel->getAllData('dispute_letters',['user_id'=>Session::get('userLoginInfo')['user_id'],'status'=>1]);
        $data['send'] = $this->masterModel->getAllData('dispute_letters',['user_id'=>Session::get('userLoginInfo')['user_id'],'status'=>2]);
        $data['complete'] = $this->masterModel->getAllData('dispute_letters',['user_id'=>Session::get('userLoginInfo')['user_id'],'status'=>3]);
        // dd($data);
    	return view('frontend.dispute',$data);
    }

    public function getDispute(Request $request){
        $data=DB::table('transactions')->whereIn('trans_id',$request->trans)->get();
        $res=[];
        foreach ($data as $key => $value) {
            if($request['type']!='new'){
                $value->desp=DB::table('dispute_letters')->where(['user_id'=>$value->user_id,'transaction_id'=>$value->trans_id,'bureau'=>$value->bureau])->orderBy('round','desc')->first();
            }else{
                $value->desp='';
            }
            $value->disputLetter = $this->masterModel->customequery('select dispute_letters.*,dispute_reasons.custom as reason,dispute_master_reasons.subject from dispute_letters left join dispute_reasons on dispute_letters.id = dispute_reasons.dispute_id left join dispute_master_reasons on dispute_reasons.dispute_reason_id = dispute_master_reasons.id where dispute_letters.user_id = '.$value->user_id.' and dispute_letters.transaction_id = '.$value->trans_id.' and dispute_letters.bureau = '.$value->bureau);
            $res[]=$value;
        }
        return $res;
    }

    public function markLetterSent(Request $request)
    {
        $avatar_name='';
        $avatar_file = $request->file('doc');
        if(!is_null($avatar_file)){
            $avatar_name = time().'_'.$avatar_file->getClientOriginalName();
            $avatar_file->move('uploads/confirm_document/',$avatar_name);
        }
        $data = $this->masterModel->updateData('dispute_letters',['id'=>$request['disputeId']],['sent_date'=>date('Y-m-d',strtotime($request['sentDate'])),'method'=>$request['method'],'confirm_doc'=>$avatar_name,'status'=>2]);
        return json_encode($data);
    }

    public function changeStatus($id)
    {
        $dispute = $this->masterModel->getGWData('dispute_letters',['id'=>$id],'confirm_doc');
        if(!$dispute)
        {
            $path = 'uploads/confirm_document/'.$dispute;
            unlink($path);
        }
        $data = $this->masterModel->updateData('dispute_letters',['id'=>$id],['sent_date'=>'0000-00-00','method'=>'','status'=>1]);
        return json_encode($data);
    }

    public function deleteDispute($id)
    {
        $data = $this->masterModel->updateData('dispute_letters',['id'=>$id],['status'=>10]);
        if (!file_exists('uploads/'.$id)) {
            rmdir('uploads/'.$id);
        }
        return json_encode($data);
    }

    public function sendDisputeMail($id)
    {
       $user = DB::table('dispute_letters')->select('register_user.id','register_user.first_name','register_user.last_name','register_user.email','register_user.address','register_user.state','register_user.pincode','cities.city','dispute_letters.created as dispute_date','transactions.*')
            ->leftjoin('register_user','dispute_letters.user_id','=','register_user.id')
            ->leftjoin('transactions','dispute_letters.transaction_id','=','transactions.trans_id')
            ->leftjoin('cities','register_user.city','=','cities.city')
            ->where('dispute_letters.id',$id)
            ->get()->first();

       $name = $user->first_name.''.$user->last_name;
       $subject = 'Dispute Letter';
       $msg = $this->invoice($user,1);
       $this->masterModel->html_email($user->email,$name,$subject,$msg);
       return json_encode(true);
    }

    public function getInvoice($id,$type)
    {
        $data = DB::table('dispute_letters')->select('register_user.id','register_user.first_name','register_user.last_name','register_user.address','register_user.state','register_user.pincode','cities.city','dispute_letters.created as dispute_date','transactions.*')
                ->leftjoin('register_user','dispute_letters.user_id','=','register_user.id')
                ->leftjoin('transactions','dispute_letters.transaction_id','=','transactions.trans_id')
                ->leftjoin('cities','register_user.city','=','cities.city')
                ->where('dispute_letters.id',$id)
                ->get()
                ->first();
            // dd($data);
            $html = $this->invoice($data,$type);

            $pdf = PDF::loadHTML($html);

            $output = $pdf->output();

            if (!file_exists('uploads/'.$id)) {
                mkdir('uploads/'.$id, 0755, true);
            }

            file_put_contents('uploads/'.$id.'/Dispute.pdf',$output);
                // $data = 'Dispute.pdf';
                // return 'Dispute.pdf';
            return $pdf->stream();
        }

        public function invoice($data,$type)
        {
            if($data->bureau==1)
                {
                    $label='Transunion';
                    $address= 'TransUnion Consumer Solutions <br>
                               P.O. Box 2000 <br>
                               Chester, PA 19016 <br>';
                }
                else if($data->bureau==2)
                {
                    $label='Experian';
                    $address= 'Experian <br>
                               P.O. Box 4500 <br>
                               Allen, TX 75013 <br>';
                }
                else
                {
                    $label='Equifax';
                    $address= 'Equifax Information Services LLC <br>
                               P.O. Box 740256 <br>
                               Atlanta, GA 30374 <br>';
                }

            $table = '';
            if($type==1)
            {
                $table .= '<table width="100%">
                                <tr>
                                    <td style="text-align: center" width="100%">
                                        <img src="'.url('/').'/accets/frontend/img/logo.png">
                                    </td>
                                </tr>
                                <tr>
                                    <td style="text-align: center;"><h3>'.$label.' Round 1 Disute Latter</h3></td>
                                </tr>
                                <tr>
                                    <td style="text-align: center;">Downloaded on '.date('d-m-Y').'</td>        
                                </tr>
                            </table>
                            <table width="100%">
                                <tr>
                                    <td>
                                        <p style="text-decoration: underline;"><b>Sending your Dispute Letter</b></p>
                                        <ol>
                                            <li>
                                                Complete your dispute letter by filling in the following information:
                                                <ul>
                                                    <li><b>Date of Birth</b> (located at the top of your dispute letter)</li>
                                                    <li><b>Social Security Number</b> (located at the top of your dispute letter)</li>
                                                    <li><b>Signature</b> (above your printed name at the bottom of your dispute letter.)</li>
                                                </ul>
                                            </li>
                                            <li>
                                                Include the following documents in your envelope:
                                                <ul>
                                                    <li><b>Dispute Letter</b> (attached)</li>
                                                    <li><b>Copy of Photo ID </b>(optional)</li>
                                                    <li><b>Proof of Address</b> (optional)</li>
                                                    <li><b>Copies of Evidence</b> to support your dispute reasons (optional)</li>
                                                </ul>
                                            </li>
                                            <li>
                                                Mail your dispute letter using standard US Mail or via Certified Mail to:
                                                <ul>
                                                    <li>
                                                        TransUnion Consumer Solutions<br>
                                                        P.O. Box 2000 <br>
                                                        Chester, PA 19016 <br>
                                                    </li>
                                                </ul>
                                            </li>
                                        </ol>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="color: #82aee2">
                                        <p style="text-decoration: underline;">Tracking your Results</p>
                                        <p>
                                            Once you’ve mailed your dispute letter, make sure to mark your letter as “SENT” in your Credit
                                            Versio account on the “DISPUTE LETTERS” page.
                                        </p>
                                        <p>
                                            Credit Versio will update your Credit Reports & Scores every 40 days and notify you of the results
                                            of your disputes, using your linked smart credit account as long as your membership is active.
                                        </p>
                                        <p>
                                            And that’s it, you’re done!
                                        </p>
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        <p style="text-align: center;"><b>Please mail your dispute letter as soon as possible for the fastest results.</b></p>
                                    </td>
                                </tr>
                            </table>';
        }

        $style = '';
        if($type==1){$style='page-break-before: always;';}

        $table .= '
                <table width="100%" style="'.$style.'">
                    <tr>
                        <td width="50%">
                            '.$data->first_name .' '.$data->last_name.'<br>
                            '.$data->address .' <br>'. $data->city .','.$data->state .','.$data->pincode.'
                        </td>
                        <td style="text-align: center;" width="50%">
                            '.date('M d, Y',strtotime($data->dispute_date)).'
                        </td>
                    </tr>
                    <tr>
                        <td width="100%">
                            Date of Birth: __/__ /____ <br>
                            SSN: _ _ _ - _ _ - _ _ _ _
                        </td>
                    </tr>
                    <tr>
                        <td width="100%">
                            <p>
                                '.$address.'
                            </p>
                            <p>Dear '.$label.',</p>
                            <p>
                                I am writing to dispute the following information that appears on my '.$label.' report from
                                07/31/2020:
                            </p>
                            <p>
                                Collection account from '.$data->creditorName.' with account #'.str_pad(substr($data->accountNumber, 0, -4), strlen($data->accountNumber), '*', STR_PAD_RIGHT).' and a balance of $'.$data->currentBalance.'. The
                                original creditor is CONWAY HOSPITAL.
                                I previously disputed this account. I dont agree with the results of your investigation. Please
                                mail me the proof of your investigation and proof this debt collector has a legal right to collect,
                                or delete this account.
                            </p>
                            <p>
                                Please reinvestigate these matters and delete or correct the disputed information as soon as
                                possible. Thank you for your assistance.
                            </p>
                            <p>Sincerely,</p>
                            <p>'.$data->first_name .' '.$data->last_name.' </p>
                        </td>
                    </tr>
                </table>';

                return $table;    
    }

    public function getTableData(Request $request)
    {
        $data = $this->masterModel->customequery('select dispute_letters.*,dispute_reasons.custom as reason,dispute_master_reasons.subject from dispute_letters left join dispute_reasons on dispute_letters.id = dispute_reasons.dispute_id left join dispute_master_reasons on dispute_reasons.dispute_reason_id = dispute_master_reasons.id where dispute_letters.user_id = '.$request['user_id'].' and dispute_letters.transaction_id = '.$request['trans_id'].' and dispute_letters.bureau = '.$request['bureau']);
        return json_encode($data);
    }
}

