<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models;
use Session;
use DB;
use Illuminate\Support\Facades\Hash;
use App\ActivityLog;
use App\Libs\Smsgateway;

class AdminController extends Controller
{
    public function index(){
        $dealers = Models\OrgUser::latest()->paginate(20);
        $data = [
            'organisations' => $dealers,
            'page_title' => 'Dealers'
        ];
        return view('super_admin.organisations',$data);
    }
    public function merchant_index(){
        $merchants = Models\Merchant::paginate(20);
        $data = [
            'merchants' => $merchants,
            'page_title' => 'Merchants'
        ];
        return view('super_admin.merchants',$data);
    }
    public function createOrg(){ //create a dealer
        $data = [
            'page_title' => 'New Dealer'
        ]; 
        return view('super_admin.create-org', $data);
    }

    /**
     * Store a newly created merchant in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request){ // save merchant in the DB

        $this->validate($request, [
            'fullname' => 'required',
            'phone_number'=> 'required|unique:merchants,phone',
            'language' => 'required'
        ]);

        $check_phone = $this->validatePhoneNumber($request->phone_number);
        if ($check_phone == false) {
            return redirect()->back()->withInput()->with('admin-error', 'Invalid phone number!');
        }
        

        $fullname = $request->input('fullname');
        $phone_number = $request->input('phone_number');
        $pin = rand(1000,9999);

        $merchant = Models\Merchant::create([
            'fullname' => $fullname,
            'phone' => $check_phone,
            'pin' => md5($pin),
            'language' => $request->language
        ]);


        $desc = [
            'title' => 'Created a merchant',
            'data' => $fullname,
            'type' => 'merchant',
        ];

        $activity = new ActivityLog;
        $activity->user_id = Auth::user()->id;
        $activity->user_type = 'admin';
        $activity->description = json_encode($desc);
        $activity->save();
        // TODO: send sms with PIN to merchant phone - 
        $msg = "You have been Successfully registered as an Airtime sales merchant. Your 4-digit PIN is $pin. You wull need it for all your activities. Dial *349# to begin.";
        $smsgateway = new Smsgateway; 
        if (env('APP_ENV') != 'local') {
            $result = $smsgateway->sendSmsNew($check_phone, $msg);
        }
        // $result = $smsgateway->sendSmsNew($check_phone, $msg);
        \Log::info($msg);
        return redirect()->to('/admin/merchant')->with('admin-sucsess', 'Successfully Added New Merchant');

    }
    public function organisationStore(Request $request){
        $this->validate($request, [
            'user_phone' => 'required',
            'user_email' => 'required',
            'user_name' => 'required',
            'country' => 'required',
            'currency' => 'required'
        ]);

    
        $generated_password = $this->randomPassword();
            
        $org_user_results = Models\OrgUser::create([
            'name' => $request->user_name,
            'phone' => $request->user_phone,
            'email' => $request->user_email,
            'country' => $request->country,
            'currency' => $request->currency,
            'added_by' => \Auth::user()->name,
            'password' => Hash::make($generated_password),
        ]);
     

        $desc = [
            'title' => 'New Dealer',
            'data' => \Auth::user()->name . ' added a new dealer with name ' . $request->name,
            'type' => 'store',
        ];

        $activity = new ActivityLog;
        $activity->user_id = \Auth::user()->id;
        $activity->user_type = 'admin';
        $activity->description = json_encode($desc);
        $activity->save();
        $login_url = env('MAIN_WEB_URL') . "/organisation"; 

        // TODO: send sms with Password to merchant phone - 
        $msg = "Hello ($request->name),  you have successfully been registered as an Airtime Sales Dealer. Your Password is $generated_password. You will need it for all your activities. \r\nLogin Here : $login_url";
        $smsgateway = new Smsgateway; 
        if (env('APP_ENV') != 'local') {
            $result = $smsgateway->sendSmsNew($check_user_phone, $msg);
        }
        \Log::info($msg);
        Session::flash('success_message', 'Dealer Successfully added!');
        return redirect()->to('/admin/organisations');
    }
     /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $dealer = Models\OrgUser::findOrfail($id);
        if (!$dealer) {
           return redirect()->back()->with('admin-error', 'Dealer not found!');
        }
        // check if the user is allowed to edit this organisation
        $data = [
            'organisation' => $dealer,
            'page_title' => 'Edit Dealer',
        ];
        return view('super_admin.organisation_edit',$data);
    }
    public function show($id)
    {
        //
        $dealer = Models\OrgUser::findOrfail($id);
        if (!$dealer) {
           return redirect()->back()->with('admin-error', 'Dealer not found!');
        }
        // check if the user is allowed to edit this organisation
        $data = [
            'organisation' => $dealer,
            'page_title' => 'Dealer Details',
        ];
        return view('super_admin.organisation_show', $data);
    }
    public function merchant_edit($id){

        $merchant = Models\Merchant::findOrfail($id);
        if (!$merchant) {
           return redirect()->back()->with('admin-error', 'Merchant not found!');
        }
        $data = [
            'merchant' => $merchant,
            'page_title' => 'Edit Merchant Details',
        ];
        return view('super_admin.merchant_edit',$data);
    }
     /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
         $this->validate($request, [
            'name' => 'required',
            'email' => 'required',
            'country' => 'required',
            'currency' => 'required',
            'phone' => [
                'required',
                'string',
                'regex:/^\+?[0-9\s\-\(\)]{7,15}$/', // Allows optional leading '+' and 7 to 15 digits/formatting characters
            ],

        ]);

        

        // dd($request->all());

        Models\OrgUser::where('id', $id)->update([
            'name' => $request->name,
            'phone' => $request->phone,
            'email' => $request->email,
            'last_modified_user_id' => \Auth::user()->id,
            'status' => $request->status,
        ]);

        $desc = [
            'title' =>'Updated Dealer details',
            'data' => $request->all(),
            'type' => 'update',
        ];

        $activity = new ActivityLog;
        $activity->user_id = \Auth::user()->id; //session('current_org_user.id');// organisation user ID
        $activity->user_type = 'super_admin';
        $activity->description = json_encode($desc);
        $activity->save();
        // dd('Activity logged');
        return redirect()->to('admin/organisations')->with('admin-success', 'Successfully Updated Dealer details');
    }
    public function merchant_update(Request $request, $id)
    {
         $this->validate($request, [
            'fullname' => 'required',
            'phone'=> 'required',
            // 'email' => 'required',
            'language' => 'required',
            'status' => 'required',
            // 'user_name' => 'required',
        ]);

        $check_phone = $this->validatePhoneNumber($request->phone);
        if ($check_phone == false) {
            return redirect()->back()->withInput()->with('admin-error', 'Invalid phone number!');
        }

        // dd($request->all());

        Models\Merchant::where('id', $id)->update([
            'fullname' => $request->fullname,
            'phone' => $check_phone,
            'language' => $request->language,
            // 'last_modified_user_id' => \Auth::user()->id,
            'status' => $request->status,
            // 'user_email' => $request->user_email,
            // 'user_name' => $request->user_name 
        ]);

        $desc = [
            'title' =>'Updated Dealer details',
            'data' => $request->all(),
            'type' => 'Merchant',
        ];

        $activity = new ActivityLog;
        $activity->user_id = \Auth::user()->id; //session('current_org_user.id');// organisation user ID
        $activity->user_type = 'merchant';
        $activity->description = json_encode($desc);
        $activity->save();
        // dd('Activity logged');
        return redirect()->to('admin/merchants')->with('admin-success', 'Successfully Updated merchant details');
    }

    public function getMerchantSales(){
        // sales from merchants to end users
        $merchant_sales = Models\Transaction::with('merchant')->latest()->paginate(30);
        $data = [
            'merchant_sales' => $merchant_sales,
            'page_title' => 'Merchant Sales'
        ];
        return view('super_admin.merchant_sales', $data);  
    }
    public function getDealerSales(){
        // sales from dealers to merchants
        $dealer_sales = Models\MerchantTopUp::with('merchantInfo', 'orgInfo')->latest()->paginate(20);
        // dd($dealer_sales);
        $data = [
            'dealer_sales' => $dealer_sales,
            'page_title' => 'Dealer Sales'
        ];
        return view('super_admin.dealer_sales', $data);  
    }
    public function AdminTransactions(){
        $data = [
            'page_title' => 'Admin Transactions'
        ];
        return view('super_admin.admin-transactions', $data);
    }
    public function getTransactionsJson(Request $request)
    {
        //$this->log_query();
        $transactions_arr = \DB::table('merchant_top_ups')
            ->join('org_users', 'merchant_top_ups.org_user_id', '=', 'org_users.id')
            ->select('merchant_top_ups.id', 'merchant_top_ups.status', 'org_users.name', 'merchant_top_ups.payment_method', 'merchant_top_ups.org_user_id', 'merchant_top_ups.amount', 'merchant_top_ups.created_at')
            ->orderBy('merchant_top_ups.created_at', 'DESC')
            ->paginate(10);

        if($request->has('keyword')){
            $queries = [];
            $keyword = $request->keyword;
            $queries['keyword'] = $keyword;
            $transactions_arr = \DB::table('merchant_top_ups')
                ->join('org_users', 'merchant_top_ups.org_user_id', '=', 'org_users.id')
                ->select('merchant_top_ups.id', 'merchant_top_ups.status', 'org_users.name', 'merchant_top_ups.payment_method', 'merchant_top_ups.org_user_id', 'merchant_top_ups.amount', 'merchant_top_ups.created_at')
                ->whereRaw("org_user.name LIKE '%$keyword%' OR merchant_top_ups.status LIKE '%$keyword%' OR merchant_top_ups.payment_method LIKE '%$keyword%' OR merchant_top_ups.amount LIKE '%$keyword%' OR merchant_top_ups.created_at LIKE '%$keyword%'")
                ->orderBy('merchant_top_ups.created_at', 'DESC')
                ->paginate(10)->appends($queries);
        }
        return response()->json($transactions_arr);
    }
    public function getAdminTransactionsJson(Request $request)
    {
        


        $query = \DB::table('organisation_top_ups')
                ->join('users', 'users.id', '=', 'organisation_top_ups.user_id')
                ->join('organisations', 'organisations.id', '=', 'organisation_top_ups.org_id')
                ->select(
                    'organisation_top_ups.id', 'organisation_top_ups.current_balance', 'organisations.balance',
                    'organisation_top_ups.amount', 'organisation_top_ups.status', 'users.name AS admin_name',
                    'organisation_top_ups.created_at', 'users.name', 'organisations.name AS dealer_name' 
                );

            if ($request->has('filter')) {
                $filters = $request->input('filter');
                
                // Map the Tabulator JS fields to the actual database table columns
                $columnMap = [
                    'admin_name'  => 'users.name',
                    'balance' => 'organisations.balance',
                    'current_balance' => 'organisation_top_ups.current_balance',
                    'amount' => 'organisation_top_ups.amount',
                    'dealer_name' => 'organisations.name'
                ];

                foreach ($filters as $filter) {
                    $field = $filter['field'];
                    $value = $filter['value'];
                    
                    // Determine the correct DB column. Default to sender_ids table to avoid 'ambiguous column' errors
                    $dbColumn = $columnMap[$field] ?? 'organisation_top_ups.' . $field;
                    
                    // Securely bind the value using Laravel's active record (prevents SQL injection)
                    $query->where($dbColumn, 'LIKE', '%' . $value . '%');
                }
            }

           

            $query->orderBy('organisation_top_ups.created_at', 'DESC');

            $perPage = $request->input('size', 15);
            $senderid_arr = $query->paginate($perPage);

            // If using the global keyword, append it to the pagination links
            if ($request->has('keyword')) {
                $senderid_arr->appends(['keyword' => $request->keyword]);
            }
            return response()->json($senderid_arr);
    }
    public function randomPassword() {
        $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
        $pass = array(); //remember to declare $pass as an array
        $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
        for ($i = 0; $i < 8; $i++) {
            $n = rand(0, $alphaLength);
            $pass[] = $alphabet[$n];
        }
        return implode($pass); //turn the array into a string
    }
}
