<?php

namespace App\Http\Controllers;

use DB;
use Str;
use Exception;
use DataTables;
use App\Models\Branch;
use App\Mail\SendEmail;
use App\Models\Customer;
use App\Mail\WelcomeMail;
use Illuminate\Http\Request;
use App\Imports\CustomerImport;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Requests\CustomerRequest;
use Illuminate\Database\QueryException;
// use Yajra\Datatables\Facades\Datatables;

class CustomerController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $this->param['pageTitle'] = 'List Member';
        $this->param['btnText'] = 'Tambah';
        $this->param['btnLink'] = route('member.create');
        $this->param['data'] = Customer::select('customer.*', 'branch.cabang', 'category')->join('branch', 'customer.id_branch', 'branch.id')->leftJoin('member_categories', 'customer.category_id', 'member_categories.id');
        $this->param['auth'] = AUTH::user()->level;

        if ($request->key) {
            $this->param['data'] = $this->param['data']->where('nama', 'like', '%' . $request->key . '%')->orWhere('email', 'like', '%' . $request->key . '%')->orWhere('phone', 'like', '%' . $request->key . '%');
        }

        $this->param['data'] = $this->param['data']->orderBy('customer.id', 'desc')->paginate(25);

        // dd($this->param['data']);

        // if ($request->ajax()) {
        //     $data = Customer::select('customer.*','branch.cabang')->join('branch', 'customer.id_branch', 'branch.id')->orderBy('customer.id','desc')->limit(10)->get();
        //     return Datatables::of($data)->addIndexColumn()
        //         ->addColumn('action', function ($row) {

        //             $btn = '<div class="form-inline btn-action">
        //             <a href="voucher/create?member=' . $row->id . '" class="mr-2">
        //                         <button type="button" id="PopoverCustomT-1" class="btn btn-rgb-success btn-sm"
        //                             data-toggle="tooltip" title="Create Voucher" data-placement="top"><span
        //                                 class="fa fa-gift fa-sm"></span></button>
        //             </a>                    
        //             <a href="member/' . $row->id . '/edit" class="mr-2">
        //                         <button type="button" id="PopoverCustomT-1" class="btn btn-rgb-primary btn-sm"
        //                             data-toggle="tooltip" title="Edit" data-placement="top"><span
        //                                 class="fa fa-edit fa-sm"></span></button>
        //                     </a>
        //                     <form action="' . route('member.destroy', $row->id) . '" method="post">
        //                         ' . csrf_field() . '
        //                         ' . method_field("DELETE") . '
        //                         <button type="submit" class="btn btn-rgb-danger btn-sm" data-toggle="tooltip"
        //                             title="Hapus" data-placement="top"
        //                             onclick="return confirm(\'Apakah anda yakin ingin menghapus ?\')">
        //                             <span class="fa fa-trash fa-sm"></span>
        //                         </button>
        //                     </form>
        //                     </div>';
        //             return $btn;
        //         })
        //         ->rawColumns(['action'])
        //         ->make(true);
        // }

        return view('customer.index', $this->param);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        $this->param['pageTitle'] = 'Tambah Member';
        $this->param['btnText'] = 'List Customer';
        $this->param['btnLink'] = route('member.index');
        $this->param['branch'] = Branch::get();
        $this->param['categories'] = \DB::table('member_categories')->get();

        if ($request->category) {
            $this->param['selectedCategory'] = \DB::table('member_categories')->where('url', $request->category);
            if ($this->param['selectedCategory']->count() == 0) {
                return back()->withError('Category tidak ditemukan.');
            } else {
                $this->param['selectedCategory'] = $this->param['selectedCategory']->first();
                return \view('customer.create-new', $this->param);
            }
        } else {
            return \view('customer.create', $this->param);
        }
        // return AUTH::user()->level;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(CustomerRequest $request)
    {
        $email_hash = Str::orderedUuid();
        $validated = $request->validated();
        $defaultPoint = \DB::table('master')->first();
        try {
            $customer = new Customer;
            $customer->nama = $validated['nama'];
            $customer->email = $validated['email'];
            $customer->phone = $validated['phone'];
            $customer->category_id = $validated['category_id'];
            $customer->tgl_lahir = $request->tgl_lahir;
            $customer->email_verified_hash = $email_hash;
            $customer->poin = $defaultPoint->default_point;
            $customer->id_branch = $validated['id_branch'];
            $customer->save();
            $details = [
                'nama_member'   => $validated['nama'],
                'confirm'       => url('confirm?verify=' . $email_hash . '&email=' . $validated['email'])
            ];
            \Mail::to($validated['email'])->send(new WelcomeMail($details));
        } catch (Exception $e) {
            return back()->withError('Terjadi kesalahan.');
        } catch (QueryException $e) {
            return back()->withError('Terjadi kesalahan pada database.');
        }

        if ($request->is_category) {
            return redirect('member/create-new?category=' . $request->is_category)->withStatus('Data berhasil disimpan. Periksa email member');
        } else {
            return redirect()->route('member.index')->withStatus('Data berhasil disimpan. Periksa email member');
        }

        return redirect()->route($url)->withStatus('Data berhasil disimpan. Periksa email member');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        if (AUTH::user()->level == 0) {
            $this->param['pageTitle'] = 'Edit Member';
            $this->param['data'] = Customer::find($id);
            $this->param['btnText'] = 'List Customer';
            $this->param['btnLink'] = route('member.index');
            $this->param['branch'] = Branch::get();
            $this->param['categories'] = \DB::table('member_categories')->get();
            return view('customer.edit', $this->param);
        } else {
            return back()->withError('Akses dilarang!!');
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $r, $id)
    {
        if (AUTH::user()->level == 0) {
            $data = Customer::findOrFail($id);

            $emailUniq = $r->email != $data->email ? '|unique:customer,email' : '';
            $phoneUniq = $r->phone != $data->phone ? '|unique:customer,phone' : '';

            $request = $r->validate(
                [
                    'nama' => 'required',
                    'id_branch' => 'required',
                    'email' => 'required' . $emailUniq,
                    'phone' => 'required' . $phoneUniq,
                    'category_id' => 'required',
                    'poin' => 'required',
                ],
                [
                    'nama.required' => 'Nama harus diisi.',
                    'email.required' => 'Email harus diisi.',
                    'email.unique' => 'Email telah digunakan.',
                    'phone.required' => 'No Telepon harus diisi.',
                    'phone.unique' => 'No Telepon telah digunakan.',
                    'id_branch.required' => 'Gerai harus diisi.',
                    'category_id.required' => 'Kategori harus diisi',
                    'poin.required' => 'Poin harus diisi'
                ]
            );

            $validated = $request;

            try {
                $data->nama = $validated['nama'];
                $data->email = $validated['email'];
                $data->phone = $validated['phone'];
                $data->category_id = $validated['category_id'];
                $data->poin = $validated['poin'];
                $data->id_branch = $validated['id_branch'];
                $data->tgl_lahir = $r->tgl_lahir;

                $data->save();
            } catch (\Exception $e) {
                return redirect()->back()->withError('Terjadi kesalahan.');
            } catch (\Illuminate\Database\QueryException $e) {
                return redirect()->back()->withError('Terjadi kesalahan pada database.');
            }

            return redirect()->route('member.index')->withStatus('Data berhasil diperbarui.');
        } else {
            return back()->withError('Akses dilarang!!');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if (AUTH::user()->level == 0) {
            try {
                $data = Customer::findOrFail($id);
                $data->delete();
            } catch (Exception $e) {
                return back()->withError('Terjadi kesalahan.');
            } catch (QueryException $e) {
                return back()->withError('Terjadi kesalahan pada database.');
            }

            return redirect()->route('member.index')->withStatus('Data berhasil dihapus.');
        } else {
            return back()->withError('Akses dilarang!!');
        }
    }

    public function cekPoin(Request $request)
    {
        $this->param['pageTitle'] = 'List Customer';

        try {
            $keyword = $request->get('keyword');
            $getData = Customer::orderBy('id');

            if ($keyword) {
                $getData->where('phone', 'LIKE', "%{$keyword}%");
            }

            $this->param['data'] = $getData->paginate(10);
        } catch (\Illuminate\Database\QueryException $e) {
            return back()->withError('Terjadi Kesalahan : ' . $e->getMessage());
        } catch (Exception $e) {
            return back()->withError('Terjadi Kesalahan pada database: ' . $e->getMessage());
        }

        return \view('customer.cek-poin', $this->param);
    }

    public function cekPoinByPhone(Request $request)
    {
        $phone = $request->get('phone');
        $getByPhone = Customer::where('phone', $phone)->orderBy('id', 'ASC')->first();
        if (empty(auth()->user()->id) && $getByPhone->email_verified_at == null) {
            return response()->json(['error' => 'Email Not Verify'], 400);
        } else {
            $customer = Customer::where('phone', $phone)->orderBy('id', 'ASC')->get();
            return $customer;
        }
    }

    public function cekPoinCustomer()
    {
        try {
            return \view('customer.cek-poin-pelanggan');
        } catch (\Illuminate\Database\QueryException $e) {
            return back()->withError('Terjadi Kesalahan : ' . $e->getMessage());
        } catch (Exception $e) {
            return back()->withError('Terjadi Kesalahan pada database: ' . $e->getMessage());
        }
    }

    public function pelangganBaru()
    {
        try {
            $data['branch'] = Branch::get();
            return \view('customer.form-pelanggan', $data);
        } catch (\Illuminate\Database\QueryException $e) {
            return back()->withError('Terjadi Kesalahan : ' . $e->getMessage());
        } catch (Exception $e) {
            return back()->withError('Terjadi Kesalahan pada database: ' . $e->getMessage());
        }
    }

    public function storePelanggan(Request $request)
    {
        $email_hash = Str::orderedUuid();
        $req = $request->validate(
            [
                'nama_member' => 'required',
                'email_member' => 'required|unique:customer,email',
                'no_hp' => 'required|unique:customer,phone',
                'id_branch' => 'required',
            ],
            [
                'nama_member.required' => 'Nama harus diisi.',
                'email_member.required' => 'Email harus diisi.',
                'email_member.unique' => 'Email telah digunakan.',
                'no_hp.required' => 'No Telepon harus diisi.',
                'no_hp.unique' => 'No Telepon telah digunakan.',
                'id_branch.required' => 'Gerai harus diisi.',
            ]
        );
        $validated = $req;
        $defaultPoint = \DB::table('master')->first();

        if (substr($validated['no_hp'], 0, 2) == '08') {
            $validated['no_hp'] = '628' . substr($validated['no_hp'], 2);
        } else {
            $validated['no_hp'] = '62' . $validated['no_hp'];
        }

        try {
            $customer = new Customer;
            $customer->nama = $validated['nama_member'];
            $customer->email = $validated['email_member'];
            $customer->phone = $validated['no_hp'];
            $customer->tgl_lahir = $request->tgl_lahir;
            $customer->id_branch = $validated['id_branch'];
            $customer->poin = $defaultPoint->default_point;
            $customer->email_verified_hash = $email_hash;
            $customer->kategori_member = $request->kategori_member != null ? $request->kategori_member : null;
            $customer->nama_komunitas = $request->nama_komunitas != null ? $request->nama_komunitas : null;
            $customer->nama_universitas = $request->nama_universitas != null ? $request->nama_universitas : null;
            $customer->nama_himpunan = $request->nama_himpunan != null ? $request->nama_himpunan : null;
            $customer->nama_perusahaan = $request->nama_perusahaan != null ? $request->nama_perusahaan : null;
            $customer->nama_sekolah = $request->nama_sekolah != null ? $request->nama_sekolah : null;
            $customer->save();
            $details = [
                'nama_member'   => $validated['nama_member'],
                'confirm'       => url('confirm?verify=' . $email_hash . '&email=' . $validated['email_member'])
            ];
            // \Mail::to($validated['email_member'])->send(new SendEmail($details));
            // \Mail::to($validated['email_member'])->send(new WelcomeMail($details));
            return redirect()->route('pelanggan-baru')->withStatus('Data berhasil disimpan. Terimakasih Sudah Bergabung Menjadi Member CoffeToffee.');
        } catch (Exception $e) {
            return back()->withError('Terjadi kesalahan.');
        } catch (QueryException $e) {
            return back()->withError('Terjadi kesalahan pada database.');
        }

        return redirect()->route('pelanggan-baru')->withStatus('Data berhasil ditambah.');
    }

    public function getConfirm(Request $request)
    {
        $data = DB::table('customer')
            ->where('email_verified_hash', $request->verify)
            ->where('email', $request->email)
            ->first();
        if ($data) {
            DB::table('customer')->where('id', $data->id)->update([
                'email_verified_at' => Date('Y:m:d H:i:s')
            ]);
            return redirect('cek-poin-pelanggan')->with('confirm', 'Email terkonfirmasi');
        } else {
            return redirect('pelanggan')->with('confirm-error', 'Konfirmasi Salah');
        }
    }

    public function postResendmail(Request $request)
    {
        $customer = Customer::where('phone', $request->phone)->first();
        if (empty($customer)) {
            return response()->json([], 400);
        }
        try {
            $details = [
                'nama_member'   => $customer->nama,
                'confirm'       => url('confirm?verify=' . $customer->email_verified_hash . '&email=' . $customer->email)
            ];
            \Mail::to($customer->email)->send(new WelcomeMail($details));
            return response()->json([], 200);
        } catch (\Throwable $th) {
            return response()->json([], 400);
        }
    }

    public function export(Request $request)
    {
        $data['member'] = Customer::select('customer.*', 'branch.cabang', 'category')->join('branch', 'customer.id_branch', 'branch.id')->leftJoin('member_categories', 'customer.category_id', 'member_categories.id')->whereBetween('customer.created_at', [$request->dari . " 00:00", $request->sampai . " 23:59"])->orderBy('id', 'asc')->get();
        header("Content-Type: application/vnd.ms-excel");
        header("Content-Disposition: attachment; filename=data-member-" . $request->dari . "_" . $request->sampai . ".xls");

        return view('customer.export', $data);
    }

    public function import(Request $request)
    {
        Excel::import(new CustomerImport(), $request->file('import_file'));
        return redirect()->route('member.index')->withStatus('Data berhasil ditambahkan.');
    }

    // public function list(Request $request)
    // {
    //     $this->param['pageTitle'] = 'List Member';
    //     $this->param['btnText'] = 'Tambah';
    //     $this->param['btnLink'] = route('transaction.create');
    //     $this->param['branch'] = Branch::get();
    //     $this->param['category'] = \DB::table('member_categories')->get();

    //     if ($request->ajax() || $request->export) {
    //         $data = Customer::select('customer.*', 'branch.cabang', 'category')->join('branch', 'customer.id_branch', 'branch.id')->leftJoin('member_categories', 'customer.category_id', 'member_categories.id');
    //         $data = $data->whereBetween('customer.created_at', [$request->dari . " 00:00", $request->sampai . " 23:59"]);

    //         if ($request->branch) {
    //             $data = $data->where('id_branch', $request->branch);
    //         }
    //         // if ($request->category) {
    //         //     $data = $data->where('category_id', $request->category);
    //         // }
    //         if ($request->kategori_member) {
    //             $data = $data->where('kategori_member', $request->kategori_member);
    //         }

    //         $data = $data->get();

    //         // dd($data);
    //         if ($request->ajax()) {
    //             return Datatables::of($data)->addIndexColumn()
    //                 // ->rawColumns(['action'])
    //                 ->make(true);
    //         } else {
    //             header("Content-type: application/vnd-ms-excel");
    //             header("Content-Disposition: attachment; filename=member_$_GET[dari]_$_GET[sampai].xls");

    //             return view('customer.export', ['member' => $data]);
    //         }
    //     }

    //     return view('customer.index-list', $this->param);
    // }


    public function list(Request $request)
    {
        $this->param['pageTitle'] = 'List Member';
        $this->param['btnText'] = 'Tambah';
        $this->param['btnLink'] = route('transaction.create');
        $this->param['branch'] = Branch::get();
        $this->param['category'] = \DB::table('member_categories')->get();

        if ($request->ajax() || $request->export) {
            $data = Customer::select(
                'customer.*',
                'branch.cabang',
                'member_categories.category', // Assuming 'category' is the name of the column in member_categories
                'customer.nama_komunitas', // Add these columns
                'customer.nama_universitas',
                'customer.nama_himpunan',
                'customer.nama_perusahaan',
                'customer.nama_sekolah'
            )
                ->join('branch', 'customer.id_branch', 'branch.id')
                ->leftJoin('member_categories', 'customer.category_id', 'member_categories.id');

            $data = $data->whereBetween('customer.created_at', [$request->dari . " 00:00", $request->sampai . " 23:59"]);

            if ($request->branch) {
                $data = $data->where('id_branch', $request->branch);
            }
            if ($request->kategori_member) {
                $data = $data->where('kategori_member', $request->kategori_member);
            }

            $data = $data->get();

            if ($request->ajax()) {
                return Datatables::of($data)->addIndexColumn()
                    ->addColumn('specific_member_data', function ($row) {
                        // This new column will dynamically show the relevant data
                        switch ($row->kategori_member) {
                            case 'komunitas':
                                return $row->nama_komunitas;
                            case 'universitas':
                                return $row->nama_universitas . ($row->nama_himpunan ? ' (' . $row->nama_himpunan . ')' : '');
                            case 'corporate':
                                return $row->nama_perusahaan;
                            case 'sekolah':
                                return $row->nama_sekolah;
                            default:
                                return '-';
                        }
                    })
                    ->rawColumns(['specific_member_data']) // If you need to render HTML in this column
                    ->make(true);
            } else {
                header("Content-type: application/vnd-ms-excel");
                header("Content-Disposition: attachment; filename=member_$_GET[dari]_$_GET[sampai].xls");

                return view('customer.export', ['member' => $data]);
            }
        }

        return view('customer.index-list', $this->param);
    }
    public function createKomunitas(Request $request)
    {
        $this->param['pageTitle'] = 'Member Komunitas dan Corporate';
        $this->param['branch'] = Branch::get();
        $this->param['selectedCategory'] = \DB::table('member_categories')->where('url', 'komunitas')->first();
        $this->param['categories'] = \DB::table('member_categories')->get();
        return \view('customer.form-member', $this->param);
    }

    public function createKaryawan(Request $request)
    {
        $this->param['pageTitle'] = 'Member Karyawan (Barista dan Management)';
        $this->param['branch'] = Branch::get();
        $this->param['selectedCategory'] = \DB::table('member_categories')->where('url', 'karyawan')->first();
        return \view('customer.form-member', $this->param);
    }


    public function createOwner(Request $request)
    {
        $this->param['pageTitle'] = 'Member Owner/Mitra Coffee Toffee';
        $this->param['branch'] = Branch::get();
        $this->param['selectedCategory'] = \DB::table('member_categories')->where('url', 'owner')->first();
        return \view('customer.form-member', $this->param);
    }

    public function storeNew(CustomerRequest $request)
    {
        $email_hash = Str::orderedUuid();
        $validated = $request->validated();
        $defaultPoint = \DB::table('master')->first();
        try {
            $customer = new Customer;
            $customer->nama = $validated['nama'];
            $customer->email = $validated['email'];
            $customer->phone = $validated['phone'];
            $customer->category_id = $validated['category_id'];
            $customer->tgl_lahir = $request->tgl_lahir;
            $customer->email_verified_hash = $email_hash;
            $customer->poin = $defaultPoint->default_point;
            $customer->id_branch = $validated['id_branch'];
            $customer->save();
            $details = [
                'nama_member'   => $validated['nama'],
                'confirm'       => url('confirm?verify=' . $email_hash . '&email=' . $validated['email'])
            ];
            \Mail::to($validated['email'])->send(new WelcomeMail($details));
        } catch (Exception $e) {
            return back()->withError('Terjadi kesalahan.');
        } catch (QueryException $e) {
            return back()->withError('Terjadi kesalahan pada database.');
        }

        return redirect($_GET['url'])->withStatus('Data berhasil disimpan. Periksa email member');
    }
}
