<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Models\BkashConfiguration;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Artisan;

class BkashController extends Controller
{

    public function getBkashInfo()
    {

        $information = BkashConfiguration::first();
        return response()->json([
            'status' => true,
            'information' => $information
        ]);
    }
    public function updateBkashInfo(Request $request)
    {

        $data = $request->validate([

            'bkash_app_key' => 'required|string',
            'bkash_app_secret' => 'required|string',
            'bkash_username' => 'required|string',
            'bkash_password' => 'required|string',
        ]);

        $callbackURL = "https://tokenized.pay.bka.sh/v1.2.0-beta";

        if (empty($data['callbackURL'])) {

            $data['callbackURL'] = $callbackURL;
        }
        if (empty($data['sandbox'])) {

            $data['sandbox'] = false;
        }
        if (empty($data['timezone'])) {

            $data['timezone'] = 'Asia/Dhaka';
        }

        $bkashSetting = BkashConfiguration::first();
        if ($bkashSetting) {
            $bkashSetting->update($data);
        } else {
            BkashConfiguration::create($data);
        }

        // Generate the configuration file with the updated values
        $file_location = config_path('bkash.php');
        $config_data = "<?php\n\nreturn [\n"
            . "    'sandbox' => " . ($data['sandbox'] ? 'true' : 'false') . ",\n"
            . "    'bkash_app_key' => '" . $data['bkash_app_key'] . "',\n"
            . "    'bkash_app_secret' => '" . $data['bkash_app_secret'] . "',\n"
            . "    'bkash_username' => '" . $data['bkash_username'] . "',\n"
            . "    'bkash_password' => '" . $data['bkash_password'] . "',\n"
            . "    'callbackURL' => '" . $data['callbackURL'] . "',\n"
            . "    'timezone' => '" . $data['timezone'] . "',\n"
            . "];";
        file_put_contents($file_location, $config_data);

        // Clear configuration cache
        Artisan::call('config:cache');
        Artisan::call('optimize:clear');
        return response()->json([
            'status' => true,
            'message' => 'Bkash Configuration Updated Successfully'
        ]);
    }

    public function updateBkashStatus(Request $request){
        $bkashSetting = BkashConfiguration::first();
        
        if($request->status==0){
            $bkashSetting->status=0;
            $bkashSetting->save();
            $message = 'Bkash De-activated successfully';
        }
        else{
            $bkashSetting->status=1;
            $bkashSetting->save();
            $message = 'Bkash Ativated successfully';
        }
        return response()->json([
            'status' => true,
            'message' => $message
        ]);
    }
}