<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Mail\InvoiceEmail;
use App\Models\PaymentListModel;
use App\Models\shp_billing_model;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\File;

class AdminProfileController extends Controller
{
    public function add_view()
    {
        return view('admin.admin_profile.ad_profile');
    }
    public function profile_view()
    {
        $admin = Auth::user();
        return view('admin.admin_profile.admin_profile_view', compact('admin'));
    }
    public function analytics_view()
    {
        return view('admin.admin_profile.ad_analytics');
    }
    public function accounting_view()
    {
        $adminList = User::where('status', 1)->get();
        return view('admin.admin_profile.ad_accounting', compact('adminList'));
    }
    public function edit_view()
    {
        $admin = Auth::user();
        return view('admin.admin_profile.edit_ad_profile', compact('admin'));
    }
    public function view_list()
    {
        $adminList = User::where('status', 1)->get();
        return view('admin.admin_profile.view_ad_list', compact('adminList'));
    }
    public function store(Request $request)
    {
        $data = $request->validate([
            'email' =>  'required|string',
            'password' =>  'required|string',
            'name' =>  'required|string',
            'shopname' =>  'required|string',
            'adress' =>  'required|string',
            'zipcode' =>  'required|string',
            'shopnumber' =>  'required|string',
            'plan_type' =>  'required|string',
            'business_hours' =>  'required|string',
            'holiday' =>  'required|string',
            'permission_number' =>  'nullable|string',


        ]);

        $existingUser = DB::table('tbl_admins')->where('email', $data['email'])->first();

        if ($existingUser) {
            return redirect()->back()
                ->withInput($request->input())
                ->withErrors(['email' => __("emailExists")]);
        }

        $addAdmin = new User;
        $addAdmin->email = $data['email'];
        $addAdmin->name = $data['name'];
        $addAdmin->password =  Hash::make($data['password']);
        $addAdmin->status = 1;
        $addAdmin->active_status = 1;
        $addAdmin->shopname = $data['shopname'];
        $addAdmin->adress = $data['adress'];
        $addAdmin->zipcode = $data['zipcode'];
        $addAdmin->dues = "0";
        $addAdmin->plan_type = $data['plan_type'];
        $addAdmin->shopnumber = $data['shopnumber'];
        $addAdmin->business_hours = $data['business_hours'];
        $addAdmin->holiday = $data['holiday'];
        $addAdmin->permission_number = $data['permission_number'] ?? "";
        if ($request->hasfile('shopimage')) {
            $file = $request->file('shopimage');
            $filename = time() . '.' . $file->getClientOriginalExtension();
            $file->move('uploads/shopImg/', $filename);
            $addAdmin->shopimage = 'uploads/shopImg/' . $filename;
        }
        // $addAdmin->shopimage = $data['shopimage'];


        $addAdmin->save();

        $this->add_lat_lng($addAdmin);
        $this->create_initial_paths($addAdmin);
        $this->add_payment_methods($addAdmin);

        $this->testbilling($addAdmin, $addAdmin->plan_type);
        // $UsersList = UserModel::all();
        // return redirect('super-admin/view-admin-list')->with('status', 'Admin Added Successfully');
        return redirect('super-admin/view-admin-list')->with('status', __("adminAdded"));
    }



    public function add_payment_methods($admin)
    {
        // Check if payment methods already exist for the shop
        $existingPayment = PaymentListModel::where('shop_id', $admin->id)->first();

        if ($existingPayment) {
            return redirect()->back()->withErrors(['email' => "Payment method already exists"]);
        }

        // Define an array of payment methods to insert
        $paymentMethods = [
            [
                'pay_method_id' => 0,
                // 'title' => 'Cash On Delivery',
                'title' => '窓口で現金お支払い',
                'img' => 'uploads/payments/1679558159.png',
                'attributes' => '-',
                'status' => 1,
                'subtitle' => '薬の受け取り時に現金でお支払いください。',
                'p_show' => 0,
            ],
            [
                'pay_method_id' => 1,
                'title' => 'Paypal',
                'img' => 'uploads/payments/1679558139.png',
                'attributes' => 'PAYPAL_KEY,1',
                'status' => 0,
                'subtitle' => 'Credit/Debit card with Easier way to pay – online and on your mobile.',
                'p_show' => 1,
            ],
            [
                'pay_method_id' => 2,
                'title' => 'カード払い',
                'img' => 'uploads/payments/1679558175.png',
                'attributes' => 'pk_test_51NacZPFnujosrfIIA6Q7JQKW4nBcPzWvoAet5HRykYI7XTrpI1woOuNCMJPPOT1OdrAbaKNk69plIpQv2V9OqvfE00pBMQLWeZ,sk_test_51NacZPFnujosrfIIXuDyE1qU2sibt919m4JcyLYwcBoSpTB2DDydLu5NlErdFjDUnWyp7tI5X0osKMyNV1vAzrLb003L0Kbw8x',
                'status' => 1,
                'subtitle' => 'クレジットカードまたはデビットカードでのお支払い。',
                'p_show' => 1,
            ],
        ];

        // Insert payment methods using a loop
        foreach ($paymentMethods as $methodData) {
            $payment = new PaymentListModel;
            $payment->fill($methodData);
            $payment->shop_id = $admin->id;
            $payment->save();
        }
    }



    public function add_lat_lng($admin)
    {
        $API_KEY = "AIzaSyBZ-7jtzy508ee_WV_8q7FyZnW84BqkqXg";
        $ADDRESS = $admin->adress;
        // $ADDRESS = utf8_encode($admin->adress);

        $url = "https://maps.googleapis.com/maps/api/geocode/json?address=" . urlencode($ADDRESS) . "&key=" . $API_KEY;

        $response = file_get_contents($url);
        $data = json_decode($response, true);

        if ($data['status'] === 'OK') {
            $latitude = $data['results'][0]['geometry']['location']['lat'];
            $longitude = $data['results'][0]['geometry']['location']['lng'];

            $admin->lat = $latitude;
            $admin->lng = $longitude;
            $admin->update();
        } else {
            $admin->lat = 0.001;
            $admin->lng = 0.001;
            $admin->update();
        }
    }


    public function create_initial_paths($shopId)
    {

        // $shopUploadsPath = public_path('../../uploads/shop_'.$shopId->id); // enable it for Live server
        $shopUploadsPath = base_path('uploads/shop_' . $shopId->id); // enable it for local server
        $medicinesPath = $shopUploadsPath . '/medicines';
        $prescriptionsPath = $shopUploadsPath . '/prescriptions';

        // Create the directories if they don't exist
        if (!File::isDirectory($medicinesPath)) {
            File::makeDirectory($medicinesPath, 0755, true);
        }

        if (!File::isDirectory($prescriptionsPath)) {
            File::makeDirectory($prescriptionsPath, 0755, true);
        }
    }

    public function update(Request $request, $admin_id)
    {


        $data = $request->validate([
            'email' =>  'required|string',
            'name' =>  'required|string',
            'password' => 'nullable|string',
            'shopname' =>  'required|string',
            'shopnumber' =>  'required|string',
            'adress' =>  'required|string',
            'zipcode' =>  'required|string',
            'plan_type' =>  'required|string',
            'business_hours' =>  'required|string',
            'holiday' =>  'required|string',
            'permission_number' =>  'nullable|string',

        ]);
        $admin = User::find($admin_id);
        $admin->email = $data['email'];
        $admin->name = $data['name'];
        if ($request->has('password') && !empty($data['password'])) {
            $admin->password = Hash::make($data['password']);
        }

        $admin->shopname = $data['shopname'];
        $admin->adress = $data['adress'];
        $admin->zipcode = $data['zipcode'];
        $admin->plan_type = $data['plan_type'];
        $admin->shopnumber = $data['shopnumber'];
        $admin->business_hours = $data['business_hours'];
        $admin->holiday = $data['holiday'];
        $admin->permission_number = $data['permission_number'] ?? "";
        if ($request->hasfile('shopimage')) {
            // $destination='uploads/payments/'.$payment_id->img;
            // echo($destination);

            // if(File::exists($destination)){
            //     File::delete($destination);
            // }

            $file = $request->file('shopimage');
            $filename = time() . '.' . $file->getClientOriginalExtension();
            $file->move('uploads/shopImg/', $filename);
            $admin->shopimage = 'uploads/shopImg/' . $filename;
        }
        $existingAdmin = User::where('email', $data['email'])
            ->where('id', '<>', $admin_id)
            ->first();

        if ($existingAdmin) {
            // return redirect()->back()->with('error', 'Email already exists for another admin');
            return redirect()->back()->with('error',  __("existsForAnotherAdmin"));
        }
        $admin->update();
        $this->add_lat_lng($admin);

        // return redirect('super-admin/view-admin-list')->with('status', 'Admin updated Successfully');
        return redirect('super-admin/view-admin-list')->with('status', __("adminUpdated"));
    }
    public function sts_update($admin_id)
    {
        //return 'This is Dashboard';
        $AdminsList =  User::find($admin_id);
        $data = request()->all();
        if ($AdminsList->active_status == 0) {
            $AdminsList->active_status = 1;
        } else {
            $AdminsList->active_status = 0;
        }



        $AdminsList->save();

        // return redirect('super-admin/view-admin-list')->with('status', 'Status updated Successfully');
        return redirect('super-admin/view-admin-list')->with('status', __("statusUpdated"));
    }
    public function delete($admin_id)
    {

        $AdminsList = User::find($admin_id);
        if ($AdminsList) {
            if ($AdminsList->delete_flag == 0) {
                $AdminsList->delete_flag = 1;
                $AdminsList->active_status = 0;
            } else {
                $AdminsList->delete_flag = 0;
            }
            $AdminsList->save();
            return redirect('super-admin/view-admin-list')->with('status', __("statusUpdated"));
        } else {
            return redirect('super-admin/view-admin-list')->with('status', __("idNotFound"));
        }
    }
    public function super_edit_view(Request $request)
    {
        $admin = $request->query('admin_id');
        $admin = User::find($admin);
        return view('admin.admin_profile.edit_ad_profile', compact('admin'));
    }

    // public function sendEmail($admin_id)
    // {
    //     $Admin = User::find($admin_id);
    //     if ($Admin) {

    //         try {
    //             // Mail::to($Admin->email)->send(new InvoiceEmail());

    //             session()->flash('status', 'Email sent successfully'); // Set success flash message
    //         } catch (\Exception $e) {
    //             session()->flash('status', 'Failed to send Email'); // Set error flash message
    //         }
    //         return redirect('super-admin/view-accounting-report');
    //     } else {
    //         return redirect('super-admin/view-accounting-report');
    //     }
    // }

    public function sendEmail($admin_id)
    {
        $Admin = User::find($admin_id);

        if ($Admin) {
            try {

                Mail::to($Admin->email)->send(new InvoiceEmail());

                session()->flash('status', 'Email sent successfully'); // Set success flash message
            } catch (\Exception $e) {
                session()->flash('status', 'Failed to send Email'); // Set error flash message
                \Log::error('Email sending error: ' . $e->getMessage());
            }
        }

        return redirect('super-admin/view-accounting-report');
    }
    public function shop_ad_billing(Request $request)
    {

        $user = Auth::user();
        // $billing_list = shp_billing_model::all();
        $billing_list = shp_billing_model::where('a_id', $user->id)->get();

        return view('admin.admin_profile.shop_ad_billing', compact('billing_list'));
    }
    public function store_shop_ad_billing()
    {

        $billing = new shp_billing_model;
        $user = Auth::user();

        $currentYear = date('Y');
        $currentMonth = date('m');

        // Get the count of records for the current year and month
        $invoiceCount = shp_billing_model::whereYear('created_at', $currentYear)
            ->whereMonth('created_at', $currentMonth)
            ->count();

        // Increment the count by one to get the next invoice number suffix
        $nextInvoiceNumberSuffix = str_pad($invoiceCount + 1, 3, '0', STR_PAD_LEFT);


        $billing->inv_no = 'INV' . substr($currentYear, -2) . $currentMonth . $nextInvoiceNumberSuffix;
        $billing->a_id = $user->id;
        $billing->month = Carbon::now()->format('F');
        $billing->due_date = "2023-03-22";


        $billing->amount = 1000;
        $user->dues = $user->dues + $billing->amount;
        $billing->status = 0;
        $billing->save();
        $user->update();


        return redirect('admin/admin-billing');
    }


    public function testbilling($adminid, $plan_type)
    {

        $billing = new shp_billing_model;
        //$user = Auth::user();
        $user = $adminid;

        $currentYear = date('Y');
        $currentMonth = date('m');

        // Get the count of records for the current year and month
        $invoiceCount = shp_billing_model::whereYear('created_at', $currentYear)
            ->whereMonth('created_at', $currentMonth)
            ->count();

        // Increment the count by one to get the next invoice number suffix
        $nextInvoiceNumberSuffix = str_pad($invoiceCount + 1, 3, '0', STR_PAD_LEFT);


        $billing->inv_no = 'INV' . substr($currentYear, -2) . $currentMonth . $nextInvoiceNumberSuffix;
        $billing->a_id = $user->id;

        $currentDate = Carbon::now();

        if ($plan_type == 0) {
            $billing->due_date =  $currentDate->addMonths(3)->toDateString();
            $billing->month = Carbon::parse($billing->due_date)->format('F');
            $billing->amount = 70000;
        } elseif ($plan_type == 1) {
            $billing->due_date =  $currentDate->addMonths(1)->toDateString();
            $billing->month = Carbon::parse($billing->due_date)->format('F');
            $billing->amount = 70000;
        } else {
            $billing->due_date =  $currentDate->addMonths(1)->toDateString();
            $billing->month = Carbon::parse($billing->due_date)->format('F');
            $billing->amount = 100000;
        }

        $user->dues = $user->dues + $billing->amount;
        $billing->status = 0;
        $billing->save();
        $user->update();


        return redirect('admin/admin-billing');
    }

    public function update_shop_ad_billing($admin_id)
    {
        $user = Auth::user();
        $billing = shp_billing_model::find($admin_id);
        $billing->status = 1;
        $billing->pay_date = Carbon::now();
        $billing->transaction_code = "ay123131msk";
        $billing->pay_method = "Stripe";
        $user->dues = $user->dues - $billing->amount;
        $billing->update();
        $user->update();

        return redirect('admin/admin-billing');
    }
    public function getBillingDetails(Request $request)
    {

        $admin_id = $request->input('admin_id');
        $billingDetails = shp_billing_model::where('a_id', $admin_id)->where('status', 1)->get();
        return response()->json($billingDetails);
    }
}
