<?php

namespace App\Http\Controllers;

use App\Http\Controllers\MainController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Services\SalesService;
use App\Services\CustomersService;
use App\Services\DeliveriesService;
use App\Models\Users\UserLogsModel;
use Illuminate\Support\Facades\Mail;

class CustomersController extends MainController
{

    public $salesSrv;
    public $customersSrv;
    public $deliversSrv;

    public function __construct(
        SalesService $salesSrv,
        DeliveriesService $deliversSrv,
        CustomersService $customersSrv
    ) {
        $this->salesSrv = $salesSrv;
        $this->customersSrv = $customersSrv;
        $this->deliversSrv = $deliversSrv;
    }
    /*
		GETS THE LIST OF ORDERS IF HAS CUSTOMER OR NOT
	*/
    public function orders(Request $request)
    {
        $json = [];
        $status = 200;
        $error = "";
        // echo "<pre>",print_r($request),"</pre>";die();
        $customer = null;
        if (!$request->user && $request->temp_user) {
            ## IF TEMP CUSTOMER GET TEMP CUSTOMER DETAILS
            $customer = $this->customersSrv->getTempCustomer($request->temp_user);
        } else if ($request->user) {
            ## IF CUSTOMER IS REGISTERED GET CUSTOMER DETAILS
            $customer = $this->customersSrv->getCustomer($request->user);
        }

        $filters = json_decode($request->filters);
        $statuses = (isset($filters->statuses) && count($filters->statuses) > 0 ? $filters->statuses : null);
        $sale_id = (isset($filters->sale_id) ? $filters->sale_id : null);
        $customer_id = (isset($customer->person_id) ? $customer->person_id : null);
        $track_number = (isset($filters->track_number) ? $filters->track_number : null);

        if ($customer_id)
            $json['orders'] = $this->deliversSrv->get($customer_id, null, $sale_id, null, $statuses, null, null, null, 50, [['col' => 'sale_id', 'sort' => 'DESC']], $track_number);

        return $this->apiResponse($json, $status, $error);
    }
    /*
		ADD TO RESERVATIONS
	*/
    public function reservations(Request $request)
    {
        $json = [];
        $status = 200;
        $error = "";

        $customer = null;
        if (!$request->user && $request->temp_user) {
            ## IF TEMP CUSTOMER GET TEMP CUSTOMER DETAILS
            $customer = $this->customersSrv->getTempCustomer($request->temp_user);
        } else if ($request->user) {
            ## IF CUSTOMER IS REGISTERED GET CUSTOMER DETAILS
            $customer = $this->customersSrv->getCustomer($request->user);
        }

        $filters = json_decode($request->filters);
        $statuses = (isset($filters->statuses) && count($filters->statuses) > 0 ? $filters->statuses : null);

        $customer_id = (isset($customer->person_id) ? $customer->person_id : null);
        //------
        if ($customer_id)
            $json['reservations'] = $this->deliversSrv->getReserations($customer_id, null, null, null, $statuses, null, null, null, 50, [['col' => 'sale_id', 'sort' => 'DESC']]);

        return $this->apiResponse($json, $status, $error);
    }
    /*
		GETS THE ORDER DETAILS BASED ON SALE ID
	*/
    public function orderView(Request $request)
    {
        $json = [];
        $status = 200;
        $error = "";

        if ($request->sale_id) {
            $order = $this->salesSrv->get($request->sale_id);
            if (!empty($order)) $json['order'] = $order;
            else $error = "Order not found";
        } else {
            $error = "Order not found";
        }

        return $this->apiResponse($json, $status, $error);
    }
    /*
		CREATES A NEW CUSTOMER
	*/
    public function add(Request $request)
    {
        $json = [];
        $status = 200;
        $error = "";

        $details = json_decode($request->details);

        if (empty($details))
            return $this->apiResponse($json, $status, 'Details not found.');

        $temp_user = ($request->temp_user ? $request->temp_user : null);

        $this->transDB(function () use (&$json, &$error, $details, $temp_user) {
            try {
                if ($details->email && $details->phone && $details->password) {
                    $error = $this->customersSrv->customerIsUnique($details->email, $details->phone);

                    if ($error == "") {
                        $customer = $this->customersSrv->addCustomer($details, $temp_user);
                        // echo "<pre>",print_r($details->email),"</pre>";die();
                        if ($customer && isset($details->address)) {
                            $this->customersSrv->addAddress($customer->id, $details->address, true);
                            $token_details = $this->customersSrv->generateToken($details->email, $customer->person_id);
                            // $to = $details->email;
                            $to_name = $details->email;
                            $to_email = $details->email;
                            // Subject
                            $data = array("token" => $token_details);

                            Mail::send('emails.verify_email', $data, function ($message) use ($to_name, $to_email) {
                                $message->to($to_email, $to_name)
                                    ->subject('PointOne Account Verification');
                                $message->from('noreply@pointone.com', 'PointOne');
                            });
                        }
                    }
                } else
                    $error = "Incomplete details.";
            } catch (\Exception $e) {
                DB::rollback();
                $error_msg = $e->getMessage();
                $error_line = $e->getLine();
                $error_file = $e->getFile();
                // $this->logError($e,$this->trans_type,$request->client_id,$request->user,"Generate Workorder");
                $error = $error_msg . " - " . $error_line . " - " . $error_file;
                // $error = "Failed to create a new account.";
            }
        });

        return $this->apiResponse($json, $status, $error);
    }
    /*
		RETURNS CUSTOMER DETAILS
	*/
    public function details(Request $request)
    {
        $json = [];
        $status = 200;
        $error = "";
        $user = $request->user;

        if ($user) {
            $customer = $this->customersSrv->getCustomer($user, true);
            if ($customer) $json['details'] = $customer;
            else $error = "User not found.";
        } else
            $error = "User not found.";
        return $this->apiResponse($json, $status, $error);
    }
    /*
		RETURNS CUSTOMER DETAILS
	*/
    public function addressAdd(Request $request)
    {
        $json = [];
        $status = 200;
        $error = "";
        $user = $request->user;
        $details = json_decode($request->details);
        if ($user) {
            $customer = $this->customersSrv->getCustomer($user);
            if ($customer && $customer->id)
                $json['address'] = $this->customersSrv->addAddress($customer->id, $details);
            else $error = "User not found.";
        } else
            $error = "User not found.";
        return $this->apiResponse($json, $status, $error);
    }
    /*
		SET DEFAULT ADDRESS
	*/
    public function addressDefault(Request $request)
    {
        $json = [];
        $status = 200;
        $error = "";
        $user = $request->user;
        $details = json_decode($request->details);
        $address_id = $request->address_id;
        if ($user) {
            $customer = $this->customersSrv->getCustomer($user);
            if ($customer && $customer->id)
                $json['default'] = $this->customersSrv->setDefaultAddress($customer->id, $address_id);

            else $error = "User not found.";
        } else
            $error = "User not found.";
        return $this->apiResponse($json, $status, $error);
    }
    /*
		DELETE ADDRESS
	*/
    public function addressDelete(Request $request)
    {
        $json = [];
        $status = 200;
        $error = "";
        $user = $request->user;
        $details = json_decode($request->details);
        $address_id = $request->address_id;
        if ($user) {
            $customer = $this->customersSrv->getCustomer($user);
            if ($customer && $customer->id)
                $json['default'] = $this->customersSrv->deleteAddress($customer->id, $address_id);

            else $error = "User not found.";
        } else
            $error = "User not found.";
        return $this->apiResponse($json, $status, $error);
    }
    /*
		RETURNS CUSTOMER NOTIFICATIOSN
	*/
    public function notifications(Request $request)
    {
        $json = [];
        $status = 200;
        $error = "";

        $customer = null;
        if (!$request->user && $request->temp_user) {
            ## IF TEMP CUSTOMER GET TEMP CUSTOMER DETAILS
            $customer = $this->customersSrv->getTempCustomer($request->temp_user);
        } else if ($request->user) {
            ## IF CUSTOMER IS REGISTERED GET CUSTOMER DETAILS
            $customer = $this->customersSrv->getCustomer($request->user);
        }
        if ($customer && $customer->person_id) {
            $last_id = ($request->last_notif_id ? $request->last_notif_id : null);
            $json = $this->customersSrv->getSalesNotifications($customer->person_id, false, 10, $last_id);
        }
        return $this->apiResponse($json, $status, $error);
    }
    /*
		RETURNS CUSTOMER NOTIFICATIOSN
	*/
    public function notificationsSeen(Request $request)
    {
        $json = [];
        $status = 200;
        $error = "";

        $customer = null;
        if (!$request->user && $request->temp_user) {
            ## IF TEMP CUSTOMER GET TEMP CUSTOMER DETAILS
            $customer = $this->customersSrv->getTempCustomer($request->temp_user);
        } else if ($request->user) {
            ## IF CUSTOMER IS REGISTERED GET CUSTOMER DETAILS
            $customer = $this->customersSrv->getCustomer($request->user);
        }

        $json = $this->customersSrv->seenSalesNotifications($customer->person_id, json_decode($request->notif_ids));
        return $this->apiResponse($json, $status, $error);
    }
    /*
		ADD TO CUSTOMER FAVORITES
	*/
    public function addRemoveFavorite(Request $request)
    {
        $json = [];
        $status = 200;
        $error = "";

        if (!$request->brand_id || !$request->menu_id) {
            $error = "brand and menu not found";
            return $this->apiResponse($json, $status, $error);
        }

        $customer = null;
        if (!$request->user && $request->temp_user) {
            ## IF TEMP CUSTOMER GET TEMP CUSTOMER DETAILS
            $customer = $this->customersSrv->getTempCustomer($request->temp_user);
        } else if ($request->user) {
            ## IF CUSTOMER IS REGISTERED GET CUSTOMER DETAILS
            $customer = $this->customersSrv->getCustomer($request->user);
        }

        if ($request->add) {
            $json = $this->customersSrv->addToFavorites($customer->person_id, $request->brand_id, $request->menu_id);
        } else
            $json = $this->customersSrv->removeToFavorites($customer->person_id, $request->brand_id, $request->menu_id);
        return $this->apiResponse($json, $status, $error);
    }


    public function updateAccount(Request $request)
    {
        $json = [];
        $status = 200;
        $error = "";
        $user = $request->user;
        // $details = json_decode($request->details);
        if ($user) {
            $customer = $this->customersSrv->getCustomer($user);
            if ($customer && $customer->id)
                $json['default'] = $this->customersSrv->updateAccount($request);

            else $error = "User not found.";
        } else
            $error = "User not found.";
        return $this->apiResponse($json, $status, $error);
    }
    public function updateAddress(Request $request)
    {
        $json = [];
        $status = 200;
        $error = "";
        $user = $request->user;
        $details = json_decode($request->details);
        // echo var_dump($details);
        if ($user) {
            $customer = $this->customersSrv->getCustomer($user);
            if ($customer && $customer->id)
                $json['default'] = $this->customersSrv->updateAddress($details);

            else $error = "User not found.";
        } else
            $error = "User not found.";
        return $this->apiResponse($json, $status, $error);
    }

    public function updateProfilePic(Request $request, $id)
    {
        $json = [];
        $status = 200;
        $error = "";
        $photo = $request->file('photo');
        if ($id) {
            $customer = $this->customersSrv->getCustomer($id);
            if ($request->hasFile('photo')) {
                if ($customer && $customer->id) {
                    $json['default'] = $this->customersSrv->updateProfilePic($id, $photo);
                } else $error = "User not found.";
            } else $error = "No image attached.";
        } else
            $error = "User not found.";
        return $this->apiResponse($json, $status, $error);
    }

    public function loyaltyCardCheck(Request $request)
    {
        $json = [];
        $status = 200;
        $error = "";

        $url = $request->url;

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_TIMEOUT => 30000,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_HTTPHEADER => array(
                // Set Here Your Requesred Headers
                'Content-Type: application/json',
            ),
        ));


        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);

        if ($err) {
            echo "cURL Error #:" . $err;
        } else {
            $json = json_decode($response);
            // print_r(json_decode($response));
        }


        return $this->apiResponse($json, $status, $error);
    }
    /*
		CREATES A NEW USER LOGS
	*/
    public function logsRecording(Request $request)
    {
        $json = [];
        $status = 200;
        $error = "";
        if ($request->current_log_id != "null") {
            $user = UserLogsModel::where('id', $request->current_log_id)->first();
            $log_1 = json_decode($user->logs);
            $log_2 = json_decode($request->logs);
            $logs = json_encode(array_merge($log_1, $log_2));
            $raw_data = $this->customersSrv->updateUserLogs($request, $logs);
            // echo "<pre>",print_r($rawurldecode(str)_data->id),"</pre>";die();
            $json['logs'] = $raw_data;
        } else {
            $logs = $request->logs;
            $json['logs'] = $this->customersSrv->addUserLogs($request, $logs);
        }

        return $this->apiResponse($json, $status, $error);
    }
    public function updateCheckoutlogs(Request $request)
    {
        $json = [];
        $status = 200;
        $error = "";
        if ($request->current_log_id != "null") {
            $raw_data = $this->customersSrv->updateUserLogsCheckout($request);
            $json['logs'] = $raw_data;
        }

        return $this->apiResponse($json, $status, $error);
    }
    public function updateCartsCreatedlogs(Request $request)
    {
        $json = [];
        $status = 200;
        $error = "";
        if ($request->current_log_id != "null") {
            $raw_data = $this->customersSrv->updateUserLogsCartsCreated($request);
            $json['logs'] = $raw_data;
        }

        return $this->apiResponse($json, $status, $error);
    }
    /*
		Send email function
	*/
    public function Mailer_testing(Request $request)
    {
        $json = [];
        $status = 200;
        $error = "";

        // $token_details = $this->customersSrv->generateToken("kronolyon@gmail.com", 130);

        $to = 'quiamconicko@gmail.com'; // note the comma
        // Subject
        // $subject = 'PointOne Account Verification';

        // Message
        $message = "
    	<html>
	    	<body>
				<div style='margin-left:60px'>
				<div style='color: #434343;font-size:26px'>Welcome to PointOne!</div>
				<img src='https://deliveryapp.point1solution.net/moment_api/public/api/store/promo/718/image' alt='Girl in a jacket' width='500' height='600'>
				<br><br>
				<div style='color: #979797;font-size:20px;'>Please click the link below to verify this email address for your PointOne account</div>
				<br>
				<a href = '#'
				style='white-space:nowrap;font-size:14px;text-decoration: none;padding: 22px 20px;background-color: #428ec0;align-items: center;color: white;border-radius: 3px;display: flex;width: 90px;'>
					Visit Our Store</a>
				<br/>
				</div>
				<hr/>
				<br/>
				<div style='margin-left:60px'><p style='color: #979797;font-size:16px;'>If you did not ask to reset your password, please disregard this email</p></div>
	    	</body>
    	</html>
    	";

        // $to1 = 'test@gmail.com';
        $subject = 'Tester subject';

        // To send HTML mail, the Content-type header must be set
        $headers[] = 'From: Moment Group <momentgroup@no-reply.com>';
        $headers[] = "Return-Path: momentgroup@sender.com";
        $headers[] = "Reply-To: The Sender <momentgroup@sender.com>";
        $headers[] = "Organization: Moment Group";
        $headers[] = 'MIME-Version: 1.0';
        $headers[] = 'Content-type: text/html; charset=iso-8859-1';
        $headers[] = "X-Priority: 3";
        $headers[] = "X-Mailer: PHP" . phpversion();
        // Mail it
        mail($to, $subject, $message, implode("\r\n", $headers));

        $json = "success";
        return $this->apiResponse($json, $status, $error);
    }
    public function EmailVerify(Request $request)
    {
        $json = [];
        $status = 200;
        $error = "";

        $token_status = $this->customersSrv->verifyToken($request->token);
        if ($token_status) {
            $json['verification_status'] = "success";
        } else {
            $json['verification_status'] = "Token is expired, do you want to resend verification email?.";
        }
        return $this->apiResponse($json, $status, $error);
    }
    /*
		resendEmail verify
	*/
    public function EmaiSendRequest(Request $request)
    {
        $json = [];
        $status = 200;
        $error = "";
        $token_details = $this->customersSrv->generateToken($request->email, $request->person_id);
        if ($token_details) {
            // $to = $request->email;
            $to_name = $request->email;
            $to_email = $request->email;
            // Subject
            // $subject = 'PointOne Account Verification';

            // Message
            if (!json_decode($request->resend_email_mode)) {
                $data = array("token" => $token_details);

                Mail::send('emails.passwordreset_email', $data, function ($message) use ($to_name, $to_email) {
                    $message->to($to_email, $to_name)
                        ->subject('PointOne Password Reset');
                    $message->from('noreply@pointone.com', 'PointOne');
                });

                echo "Email Sent. Check your inbox.";
                $json = "success";
                // $subject = 'PointOne Password Reset';
            } else {
                $data = array("token" => $token_details);

                Mail::send('emails.verify_email', $data, function ($message) use ($to_name, $to_email) {
                    $message->to($to_email, $to_name)
                        ->subject('PointOne Account Verification');
                    $message->from('noreply@pointone.com', 'PointOne');
                });

                echo "Email Sent. Check your inbox.";
                $json = "success";
                // $subject = 'PointOne Account Verification';
            }
        }
        return $this->apiResponse($json, $status, $error);
    }
    public function contactus_email(Request $request)
    {
        $json = [];
        $status = 200;
        $error = "";
        $to_name = 'Speakfreely';
        $to_email = 'speakfreely@momentgroup.ph';
        $data = array('full_name' => $request->full_name, "email" => $request->email, "subject" => $request->email, "message_body" => $request->message);

        Mail::send('emails.contact_us', $data, function ($message) use ($to_name, $to_email) {
            $message->to($to_email, $to_name)
                ->subject('Customer inquiry');
            $message->from('noreply@pointone.com', 'PointOne');
        });

        echo "Email Sent. Check your inbox.";

        $json = "success";
        return $this->apiResponse($json, $status, $error);
    }
    public function mail()
    {
        $json = [];
        $status = 200;
        $error = "";
        $to_name = 'Nicko Quiamco';
        $to_email = 'quiamconicko@gmail.com';
        $data = array('name' => "", "body" => "Test mail");

        Mail::send('emails.mail', $data, function ($message) use ($to_name, $to_email) {
            $message->to($to_email, $to_name)
                ->subject('PointOne');
            $message->from('noreply@pointone.com', 'PointOne');
        });

        echo "Email Sent. Check your inbox.";
        $json = "success";
        return $this->apiResponse($json, $status, $error);
    }
}
