<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Imports\CdsImport;
use App\Imports\OffplanImport;
use App\Models\CallingDatabase;
use App\Models\Contact;
use App\Models\Lead;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Response;

class SetupController extends Controller
{
    public function citiesView()
    {
        return view('admin.cities.cities');
    }

    public function locationsView()
    {
        return view('admin.locations.locations');
    }

    public function purposesView()
    {
        return view('admin.purposes.purposes');
    }

    public function propertyTypesView()
    {
        return view('admin.propertyTypes.propertyTypes');
    }

    public function unitTypesView()
    {
        return view('admin.unitTypes.unitTypes');
    }

    public function featuresView()
    {
        return view('admin.features.features');
    }

    public function completionStatusView()
    {
        return view('admin.completionStatuses.completionStatuses');
    }

    public function developmentStatusView()
    {
        return view('admin.developmentStatuses.developmentStatuses');
    }

    public function saleStatusView()
    {
        return view('admin.saleStatuses.saleStatuses');
    }

    public function ownershipStatusView()
    {
        return view('admin.ownershipStatuses.ownershipStatuses');
    }

    public function rentFrequenciesView()
    {
        return view('admin.rentFrequencies.rentFrequencies');
    }

    public function chequesView()
    {
        return view('admin.cheques.cheques');
    }

    public function districtsView()
    {
        return view('admin.districts.districts');
    }

    public function projectsView()
    {
        return view('admin.projects.projects');
    }

    public function developersView()
    {
        return view('admin.developers.developers');
    }

    public function settingsView()
    {
        return view('admin.settings.profile');
    }

    public function leadStatusView()
    {
        return view('admin.leadStatuses.leadStatuses');
    }

    public function leadTypesView()
    {
        return view('admin.leadTypes.leadTypes');
    }

    public function leadCategoriesView()
    {
        return view('admin.leadCategories.leadCategories');
    }

    public function leadInterestLevelsView()
    {
        return view('admin.leadInterestLevels.leadInterestLevels');
    }

    public function leadSourcesView()
    {
        return view('admin.leadSources.leadSources');
    }

    public function enquirySourcesView()
    {
        return view('admin.enquirySources.enquirySources');
    }

    public function contactRolesView()
    {
        return view('admin.contactRoles.contactRoles');
    }

    public function cdView()
    {
        return view('admin.callingDatabase.callingDatabase');
    }

    public function leadsView()
    {
        return view('admin.leads.leads');
    }

    public function leadDetailsView($id)
    {
        $lead = auth()->user()->leads()->findOrFail($id);
        return view('admin.leads.leadDetails', ['lead' => $lead]);
    }

    public function contactsView()
    {
        return view('admin.contacts.contacts');
    }

    public function contactDetailsView($id)
    {
        $contact = auth()->user()->contacts()->findOrFail($id);
        return view('admin.contacts.contactDetails', ['contact' => $contact]);
    }

    public function reqView()
    {
        return view('admin.requirements.requirements');
    }

    public function offplanView()
    {
        return view('admin.offplan.offplan');
    }

    public function appointmentsView()
    {
        return view('admin.appointments.appointments');
    }

    public function calenderView()
    {
        return view('admin.calender.calender');
    }

    public function uploadCdsFile(Request $request)
    {
        $validator = \Illuminate\Support\Facades\Validator::make($request->all(), [
            'file' => 'required|file|mimes:xls,xlsx',
        ]);
        if ($validator->fails()) {
            return redirect(url()->previous())->with('errors', $validator->messages()->all());
        }
        try {
            Excel::import(new CdsImport, $request->file('file'));
            return redirect()->back()->with('success', 'File successfully uploaded.');
        } catch (\Exception $e) {
//            return redirect()->back()->with('errors', [$e->getMessage()]);
            return redirect()->back()->with('errors', ['Header for excel sheet should be like this: Name,Email,Phone,Unit Number,Tower,Area,City,Property Type']);
        }
    }

    public function uploadOffplanFile(Request $request)
    {
        $validator = \Illuminate\Support\Facades\Validator::make($request->all(), [
            'file' => 'required|file|mimes:xls,xlsx',
        ]);
        if ($validator->fails()) {
            return redirect(url()->previous())->with('errors', $validator->messages()->all());
        }
        try {
            Excel::import(new OffplanImport(), $request->file('file'));
            return redirect()->back()->with('success', 'File successfully uploaded.');
        } catch (\Exception $e) {
            return redirect()->back()->with('errors', ['Header for excel sheet should be like this: Project Name,Developer Number,Unit Type,Development Status,Sale Status,Unit Number,Floor,View,Price,Area,Unit Area,Beds,Parking,Completion Date']);
        }
    }

    public function exportCds(Request $request)
    {
        $cdsList = CallingDatabase::where('added_by', auth()->id());
        if ($request->has('cd_status_search') && $request['cd_status_search'] != '' && $request['cd_status_search'] != 'null' && $request['cd_status_search'] != 'undefined') {
            $cdsList->whereIn('cd_status_id', $request['cd_status_search']);
        }
        if ($request->has('cd_category_search') && $request['cd_category_search'] != '' && $request['cd_category_search'] != 'null' && $request['cd_category_search'] != 'undefined') {
            $cdsList->whereIn('cd_category_id', $request['cd_category_search']);
        }
        if ($request->has('pt_search') && $request['pt_search'] != '' && $request['pt_search'] != 'null' && $request['pt_search'] != 'undefined') {
            $cdsList->where('property_type', $request['pt_search']);
        }
        if ($request->has('at_search') && $request['at_search'] != '' && $request['at_search'] != 'null' && $request['at_search'] != 'undefined') {
            $cdsList->whereIn('assign_to', $request['at_search']);
        }
        if ($request->has('from_search') && $request['from_search'] != '' && $request->has('to_search') && $request['to_search'] != '') {
            $cdsList->whereBetween('reference_number', [$request['from_search'], $request['to_search']]);
        }
        if ($request->has('assign_search') && $request['assign_search'] != '' && $request['assign_search'] != 'null' && $request['assign_search'] != 'undefined') {
            if ($request['assign_search'] == 1) {
                $cdsList->whereNotNull('assign_to');
            }
            if ($request['assign_search'] == 2) {
                $cdsList->whereNull('assign_to');
            }
        }
        $models = $cdsList->get();
        $filename = "calling_db_" . date('Y-m-d') . ".csv";
        return Response::streamDownload(function () use ($models) {
            $handle = fopen('php://output', 'w');
            fputcsv($handle, [
                'Ref.',
                'Name',
                'Email',
                'Phone',
                'Unit Number',
                'Tower',
                'Area',
                'City',
                'Property Type',
                'Assigned To',
                'Status',
                'Category',
            ]);
            foreach ($models as $model) {
                fputcsv($handle, [
                    $model->reference_number ?? '',
                    $model->name ?? '',
                    $model->email ?? '',
                    $model->phone ?? '',
                    $model->unit_no ?? '',
                    $model->tower ?? '',
                    $model->district ?? '',
                    $model->city ?? '',
                    $model->property_type ?? '',
                    $model->assignee ? $model->assignee->name : '',
                    $model->cd_status ? $model->cd_status->name : '',
                    $model->cd_category ? $model->cd_category->name : ''
                ]);
            }
            fclose($handle);
        }, $filename, [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
            'Pragma' => 'no-cache',
            'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
            'Expires' => '0'
        ]);
    }

    public function exportLeads()
    {
        $models = Lead::where('added_by', auth()->id())->get();
        $filename = "leads_" . date('Y-m-d') . ".csv";
        return Response::streamDownload(function () use ($models) {
            $handle = fopen('php://output', 'w');
            fputcsv($handle, [
                'Ref.',
                'Title',
                'Name',
                'Email',
                'Phone',
                'Property Type',
                'Lead Type',
                'Lead Category',
                'Lead Status',
                'Primary Source',
                'Secondary Source',
                'Lead Interest Level',
                'Assign To',
                'Additional info',
            ]);
            foreach ($models as $model) {
                fputcsv($handle, [
                    $model->reference_number ?? '',
                    $model->title ?? '',
                    $model->name ?? '',
                    $model->email ?? '',
                    $model->phone ?? '',
                    $model->property_type ? $model->property_type->name : '',
                    $model->lead_type ? $model->lead_type->name : '',
                    $model->lead_category ? $model->lead_category->name : '',
                    $model->lead_status ? $model->lead_status->name : '',
                    $model->lead_primary_source ? $model->lead_primary_source->name : '',
                    $model->lead_secondary_source ? $model->lead_secondary_source->name : '',
                    $model->lead_interest_level ? $model->lead_interest_level->name : '',
                    $model->assignee ? $model->assignee->name : '',
                    $model->description ?? '',
                ]);
            }
            fclose($handle);
        }, $filename, [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
            'Pragma' => 'no-cache',
            'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
            'Expires' => '0'
        ]);
    }

    public function exportContacts()
    {
        $models = Contact::where('added_by', auth()->id())->get();
        $filename = "contacts_" . date('Y-m-d') . ".csv";
        return Response::streamDownload(function () use ($models) {
            $handle = fopen('php://output', 'w');
            fputcsv($handle, ['Type', 'Title', 'Name', 'Phone', 'Alt. Phone', 'Email', 'BRN', 'ORN', 'TLN', 'Address', 'Website', 'Source', 'Contact Role', 'Assigned To']);
            foreach ($models as $model) {
                fputcsv($handle, [
                    $model->type == 1 ? 'Individual' : 'Company',
                    $model->salutation,
                    $model->name,
                    $model->phone,
                    $model->alt_phone,
                    $model->email,
                    $model->brn,
                    $model->orn,
                    $model->tln,
                    $model->address,
                    $model->website,
                    $model->source ? $model->source->name : '',
                    $model->contact_role ? $model->contact_role->name : '',
                    $model->assignee ? $model->assignee->name : ''
                ]);
            }
            fclose($handle);
        }, $filename, [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
            'Pragma' => 'no-cache',
            'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
            'Expires' => '0'
        ]);
    }
}
