<?php

namespace App\Http\Controllers;

use App\Http\Requests\TransactionRequest;
use App\Models\Transaction;
use App\Models\Customer;
use App\Models\Branch;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Database\QueryException;
use DataTables;


class TransactionController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    // public function index(Request $request)
    // {
    //     $this->param['pageTitle'] = 'List Transaksi';
    //     $this->param['btnText'] = 'Tambah';
    //     $this->param['btnLink'] = route('transaction.create');

    //     if ($request->ajax()) {
    //         $data = Transaction::select('voucher_code', 'transaction.id', 'transaction.trx_code', \DB::raw('CASE WHEN transaction.tipe = "0" THEN "Transaksi POS" WHEN transaction.tipe = "1" THEN "Penukaran Voucher" END AS tipe'), 'customer.nama', 'transaction.poin', 'transaction.tgl_trx', 'transaction.created_at', 'transaction.tgl_trx', 'branch.cabang', 'voucher_price', 'amount', 'poin_earned')
    //             ->leftJoin('customer', 'customer.id', 'transaction.id_cust')
    //             ->leftJoin('branch', 'branch.id', 'transaction.id_branch')
    //             ->whereBetween('tgl_trx', [$request->dari . " 00:00", $request->sampai . " 23:59"])
    //             ->get();
    //         return Datatables::of($data)->addIndexColumn()
    //             ->addColumn('action', function ($row) {

    //                 $btn = '<div class="form-inline btn-action">
    //                 <a href="transaction/' . $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('transaction.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('transaction.index', $this->param);
    // }

    protected $param = []; // Initialize param property

    public function index(Request $request)
    {
        $this->param['pageTitle'] = 'List Transaksi';
        $this->param['btnText'] = 'Tambah';
        $this->param['btnLink'] = route('transaction.create');

        // Fetch data for filter dropdowns
        $this->param['branch'] = Branch::get();
        // Assuming member_categories is needed for a full list,
        // but for dynamic dropdown, the hardcoded options are fine.
        // $this->param['category'] = \DB::table('member_categories')->get();

        if ($request->ajax()) {
            $data = Transaction::select(
                'voucher_code',
                'transaction.id',
                'transaction.trx_code',
                \DB::raw('CASE WHEN transaction.tipe = "0" THEN "Transaksi POS" WHEN transaction.tipe = "1" THEN "Penukaran Voucher" END AS tipe'),
                'customer.nama',
                'transaction.poin',
                'transaction.tgl_trx',
                'transaction.created_at',
                'transaction.tgl_trx',
                'branch.cabang',
                'voucher_price',
                'amount',
                'poin_earned',
                'customer.kategori_member', // Select kategori_member from customer
                'customer.nama_komunitas', // Select specific member data
                'customer.nama_universitas',
                'customer.nama_himpunan',
                'customer.nama_perusahaan',
                'customer.nama_sekolah'
            )
                ->leftJoin('customer', 'customer.id', 'transaction.id_cust')
                ->leftJoin('branch', 'branch.id', 'transaction.id_branch');

            // Apply date range filter
            $data = $data->whereBetween('tgl_trx', [$request->dari . " 00:00:00", $request->sampai . " 23:59:59"]);

            // Apply branch filter
            if ($request->branch) {
                $data = $data->where('transaction.id_branch', $request->branch);
            }

            // Apply kategori_member filter and specific member type filters
            if ($request->kategori_member) {
                $data = $data->where('customer.kategori_member', $request->kategori_member);

                if ($request->kategori_member == 'komunitas' && $request->nama_komunitas) {
                    $data = $data->where('customer.nama_komunitas', 'like', '%' . $request->nama_komunitas . '%');
                } elseif ($request->kategori_member == 'universitas' && $request->nama_universitas) {
                    $data = $data->where('customer.nama_universitas', 'like', '%' . $request->nama_universitas . '%');
                    if ($request->nama_himpunan) {
                        $data = $data->where('customer.nama_himpunan', 'like', '%' . $request->nama_himpunan . '%');
                    }
                } elseif ($request->kategori_member == 'corporate' && $request->nama_perusahaan) {
                    $data = $data->where('customer.nama_perusahaan', 'like', '%' . $request->nama_perusahaan . '%');
                } elseif ($request->kategori_member == 'sekolah' && $request->nama_sekolah) {
                    $data = $data->where('customer.nama_sekolah', 'like', '%' . $request->nama_sekolah . '%');
                }
            }

            $data = $data->get();

            return Datatables::of($data)->addIndexColumn()
                ->addColumn('action', function ($row) {
                    $btn = '<div class="form-inline btn-action">
                    <a href="transaction/' . $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('transaction.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;
                })
                ->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(['action', 'specific_member_data'])
                ->make(true);
        }
        return \view('transaction.index', $this->param);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $this->param['pageTitle'] = 'Tambah Transaksi';
        $this->param['btnText'] = 'List Transaksi';
        $this->param['btnLink'] = route('transaction.index');
        $this->param['data'] = Customer::get();
        $this->param['cabang'] = Branch::get();
        $this->param['persentase'] = \DB::table('master')->first();

        return \view('transaction.create', $this->param);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(TransactionRequest $request)
    {
        $validated = $request->validated();
        try {
            $transaction = new Transaction;
            $transaction->trx_code = $validated['trx_code'];
            $transaction->id_cust = $validated['id_cust'];
            $transaction->poin = $validated['poin'];
            $transaction->amount = $validated['amount'];
            $transaction->tipe = $request->input('tipe');
            $transaction->tgl_trx = $request->input('tgl_trx');
            $transaction->id_branch = $request->input('id_branch');
            $transaction->save();

            if ($request->input('tipe') == '0') {
                $customer = Customer::find($validated['id_cust']);
                $customer->poin = $customer->poin + $validated['poin'];
                $customer->save();
                // ddd('ditambah');
            } else {
                // ddd('dikurangi');
                $customer = Customer::find($validated['id_cust']);
                $customer->poin = $customer->poin - $validated['poin'];
                $customer->save();
            }

            \DB::table('master')->update(['percent' => $request->persentase]);
            // ddd($customer->poin);
        } catch (Exception $e) {
            return back()->withError('Terjadi kesalahan.');
        } catch (QueryException $e) {
            return back()->withError('Terjadi kesalahan pada database.');
        }

        return redirect()->route('transaction.index')->withStatus('Data berhasil disimpan.');
    }

    /**
     * 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)
    {
        $this->param['pageTitle'] = 'Edit Transaksi';
        $this->param['btnText'] = 'List Transaksi';
        $this->param['btnLink'] = route('transaction.index');
        $this->param['data'] = Transaction::find($id);
        $this->param['user'] = Customer::get();
        $this->param['cabang'] = Branch::get();
        // ddd($this->param['data']);
        return \view('transaction.edit', $this->param);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $data = Transaction::findOrFail($id);
        $validated = $request;
        $oldPoin = $validated['poin'] - $data->poin;
        $member = Customer::find($data->id_cust);
        $customer = Customer::find($data->id_cust);
        // ddd($validated['poin'] > $data->poin);

        try {
            if ($data->tipe == '0') {
                if ($validated['poin'] > $data->poin) {
                    $customer->poin = $member->poin + $oldPoin;
                } else {
                    $customer->poin = $member->poin - ($data->poin - $validated['poin']);
                    // ddd($customer->poin);
                }
            } else {
                if ($validated['poin'] > $data->poin) {
                    $customer->poin = $member->poin - $oldPoin;
                } else {
                    $customer->poin = $data->poin - $validated['poin'] + $member->poin;
                    // ddd($data->poin - $validated['poin']+$member->poin);
                }
            }
            $customer->save();
            $data->trx_code = $validated['trx_code'];
            $data->id_cust = $validated['id_cust'];
            $data->amount = $validated['amount'];
            $data->poin = $validated['poin'];
            $data->tgl_trx = $request->input('tgl_trx');
            $data->id_branch = $request->input('id_branch');
            $data->save();
            \DB::table('master')->update(['percent' => $request->persentase]);
        } catch (\Exception $e) {
            return redirect()->back()->withError('Terjadi kesalahan.' . $e);
        } catch (\Illuminate\Database\QueryException $e) {
            return redirect()->back()->withError('Terjadi kesalahan pada database.');
        }

        return redirect()->route('transaction.index')->withStatus('Data berhasil diperbarui.');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        try {
            $transaction = Transaction::findOrFail($id);
            $customer = Customer::findOrFail($transaction->id_cust);
            // ddd($transaction->id_cust);
            $transaction->delete();
            \DB::table('customer')->where('id', $transaction->id_cust)->update((array('poin' => $customer->poin - $transaction->poin)));
        } catch (Exception $e) {
            return back()->withError('Terjadi kesalahan.' . $e);
        } catch (QueryException $e) {
            return back()->withError('Terjadi kesalahan.' . $e);
        }

        return redirect()->route('transaction.index')->withStatus('Data berhasil dihapus.');
    }

    // public function redeem(Request $request)
    // {
    //     $this->param['branch'] = Branch::get();

    //     if ($request->ajax()) {
    //         $data = Transaction::select('voucher_code', 'transaction.id', 'transaction.trx_code', \DB::raw('CASE WHEN transaction.tipe = "0" THEN "Transaksi POS" WHEN transaction.tipe = "1" THEN "Penukaran Voucher" END AS tipe'), 'customer.nama', 'transaction.poin', 'transaction.tgl_trx', 'transaction.created_at', 'transaction.tgl_trx', 'branch.cabang', 'voucher_price', 'amount', 'poin_earned')
    //             ->leftJoin('customer', 'customer.id', 'transaction.id_cust')
    //             ->leftJoin('branch', 'branch.id', 'transaction.id_branch')
    //             ->whereBetween('tgl_trx', [$request->dari . " 00:00", $request->sampai . " 23:59"])->where('tipe', '1');
    //         if ($request->cabang) {
    //             $data = $data->where('transaction.id_branch', $request->cabang);
    //         }
    //         $data = $data->get();
    //         return Datatables::of($data)->addIndexColumn()
    //             ->addColumn('action', function ($row) {

    //                 $btn = '<div class="form-inline btn-action">
    //                 <a href="transaction/' . $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('transaction.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('transaction.redeem', $this->param);
    // }

    public function redeem(Request $request)
    {
        // Set page title and other common parameters if needed for this view
        $this->param['pageTitle'] = 'List Penukaran Voucher';
        // $this->param['btnText'] = 'Tambah'; // Uncomment if you have an add button for redeem
        // $this->param['btnLink'] = route('transaction.create_redeem'); // Adjust route if needed

        // Fetch data for filter dropdowns
        $this->param['branch'] = Branch::get();
        // $this->param['category'] = \DB::table('member_categories')->get(); // Uncomment if you need this for the view

        if ($request->ajax()) {
            $data = Transaction::select(
                'voucher_code',
                'transaction.id',
                'transaction.trx_code',
                \DB::raw('CASE WHEN transaction.tipe = "0" THEN "Transaksi POS" WHEN transaction.tipe = "1" THEN "Penukaran Voucher" END AS tipe'),
                'customer.nama',
                'transaction.poin', // This 'poin' is likely the points used for redemption
                'transaction.tgl_trx',
                'transaction.created_at',
                'branch.cabang',
                'voucher_price',
                'amount', // This 'amount' is likely the value of the redeemed voucher
                'poin_earned', // This might be zero for redemption, but included for completeness
                'customer.kategori_member', // Select kategori_member from customer
                'customer.nama_komunitas', // Select specific member data
                'customer.nama_universitas',
                'customer.nama_himpunan',
                'customer.nama_perusahaan',
                'customer.nama_sekolah'
            )
                ->leftJoin('customer', 'customer.id', 'transaction.id_cust')
                ->leftJoin('branch', 'branch.id', 'transaction.id_branch')
                ->where('transaction.tipe', '1'); // Filter for 'Penukaran Voucher'

            // Apply date range filter
            if ($request->has('dari') && $request->has('sampai')) {
                $data = $data->whereBetween('tgl_trx', [$request->dari . " 00:00:00", $request->sampai . " 23:59:59"]);
            }


            // Apply branch filter
            if ($request->branch) { // Changed from $request->cabang to $request->branch for consistency
                $data = $data->where('transaction.id_branch', $request->branch);
            }

            // Apply kategori_member filter and specific member type filters
            if ($request->kategori_member) {
                $data = $data->where('customer.kategori_member', $request->kategori_member);

                if ($request->kategori_member == 'komunitas' && $request->nama_komunitas) {
                    $data = $data->where('customer.nama_komunitas', 'like', '%' . $request->nama_komunitas . '%');
                } elseif ($request->kategori_member == 'universitas' && $request->nama_universitas) {
                    $data = $data->where('customer.nama_universitas', 'like', '%' . $request->nama_universitas . '%');
                    if ($request->nama_himpunan) {
                        $data = $data->where('customer.nama_himpunan', 'like', '%' . $request->nama_himpunan . '%');
                    }
                } elseif ($request->kategori_member == 'corporate' && $request->nama_perusahaan) {
                    $data = $data->where('customer.nama_perusahaan', 'like', '%' . $request->nama_perusahaan . '%');
                } elseif ($request->kategori_member == 'sekolah' && $request->nama_sekolah) {
                    $data = $data->where('customer.nama_sekolah', 'like', '%' . $request->nama_sekolah . '%');
                }
            }

            $data = $data->get();

            return Datatables::of($data)->addIndexColumn()
                ->addColumn('action', function ($row) {
                    $btn = '<div class="form-inline btn-action">
                        <a href="transaction/' . $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('transaction.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;
                })
                ->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(['action', 'specific_member_data'])
                ->make(true);
        }
        return \view('transaction.redeem', $this->param);
    }
}
