<?php

namespace App\Http\Controllers\Trancation;

use App\Http\Controllers\Controller;
use App\Models\JobQueue;
use App\Models\ProvinceAndCity\CityModel;
use App\Models\TransactionModel;
use App\Models\WalletModel;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Carbon\CarbonTimeZone;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Nette\Utils\Random;

class TransactionController extends Controller
{
    //

    public function insert(Request $request)
    {
        $data = $request->json()->all();
        $user = Auth::user();

        if (!isset($data['data'])) {
            return response()->json(['status' => 0, 'message' => 'دیتا الزامیست!', 'code' => 666]);
        }

        $array = $data['data'];

        if (!is_array($array)) {
            return response()->json(['status' => 0, 'message' => 'فرمت داده‌ها نادرست است!', 'code' => 667]);
        }

        $updatedArray = [];

        DB::beginTransaction();

        try {
            foreach ($array as $item) {
                $wallet_id = $item['wallet_id'];
                $tracking_id = $item['isIncrease'] ? $item['qrId'] : $this->generateTrackingId();

                // پیدا کردن مدل کیف پول
                $walletModel = WalletModel::find($wallet_id);

                if (!$walletModel) {
                    DB::rollBack();
                    return response()->json(['status' => 0, 'message' => 'کیف پول کاربر یافت نشد']);
                }

                // دریافت و محاسبه اعتبار کیف پول
                $walletCredit = $walletModel->credit;
                if ($item['isIncrease']) {
                    $walletCredit += $item['price'];
                } else {
                    $walletCredit -= $item['price'];
                }

                // پیدا کردن مدل شهر
                $city = CityModel::find($walletModel->city_id);
                if (!$city) {
                    DB::rollBack();
                    return response()->json(['status' => 0, 'message' => 'شهر مرکز یافت نشد']);
                }

                $transaction_id = $this->generateTransactionId();


                $item['transaction_id'] = $transaction_id;
                $item['tracking_id'] = $tracking_id;
                $item['user_id'] = $user->id;

                $checkExisingDateTime = TransactionModel::where('dateTime', $item['dateTime'])->first();
                if (!$checkExisingDateTime) {
                    $transaction = new TransactionModel([
                        'user_id' => $item['user_id'],
                        'cardId' => $item['cardId'],
                        'dateTime' => $item['dateTime'],
                        'price' => $item['price'],
                        'transaction_id' => $transaction_id,
                        'tracking_id' => $tracking_id,
                        'preCredit' => $item['preCredit'],
                        'afterCredit' => $item['afterCredit'],
                        'uc' => $item['uc'],
                        'lineId' => $item['lineId'],
                        'qrId' => $item['qrId'],
                        'isIncrease' => $item['isIncrease'],
                    ]);
                    if (!$transaction->save()) {
                        // عملیات ذخیره‌سازی موفقیت‌آمیز بود
                        return response()->json(['status' => 0, 'message' => 'خطا در ذخیره سازی داده ها پایگاه داده داخلی']);
                    }
                    $item['isIncrease'] = (boolean)$item['isIncrease'];

                    $updatedArray[] = $item;
                    // ذخیره تغییرات مدل کیف پول
                    $walletModel->credit = $walletCredit;
                    $walletModel->save();
                    // ارسال به سرور SQL Server
                    $this->sendToSqlServer(
                        $item,
                        $tracking_id,
                        $transaction_id,
                        $city->ip_address,
                        $city->username,
                        $city->password,
                        $city->id,
                        $walletCredit,
                        $city->uc
                    );

                }





            }

            DB::commit();

            if (count($updatedArray) == 0){
                return response()->json(['status' => 0, 'message' => 'تراکنشی جهت ثبت وجود ندارد یا تاریخ تراکنش تکراریست'], 200);

            }

            return response()->json(['status' => 1, 'message' => 'تراکنش با موفقیت ثبت شد', 'data' => (object)['transaction' => $updatedArray]], 200);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['status' => 0, 'message' => 'خطا در ثبت تراکنش', 'error' => $e->getMessage()], 500);
        }
    }

    public function getAllTransactions(Request $request)
    {
        $transactions = TransactionModel::get();
        if (count($transactions) > 0) {

            foreach ($transactions as $transaction) {
                // تبدیل مقدار isIncrease به نوع boolean
                $transaction->isIncrease = (boolean)$transaction->isIncrease;
            }

            return response()->json(['status' => 0, 'message' => 'لیست تراکنشات', 'data' => (object)['transaction' => $transactions]], 200);

        } else {
            return response()->json(['status' => 0, 'message' => 'در سیستم تراکنشی به ثبت نرسیده است'], 403);
        }
    }

    public function getUserTransactions(Request $request)
    {
        $user = Auth::user();
        $transactions = TransactionModel::where('user_id', $user->id)->get();
        if (count($transactions) > 0) {

            foreach ($transactions as $transaction) {
                // تبدیل مقدار isIncrease به نوع boolean
                $transaction->isIncrease = (boolean)$transaction->isIncrease;
            }
            return response()->json(['status' => 0, 'message' => 'لیست تراکنشات شما', 'data' => (object)['transaction' => $transactions]], 200);

        } else {
            return response()->json(['status' => 0, 'message' => 'تراکنشی برای شما به ثبت نرسیده است'], 403);
        }
    }


    public function sendToSqlServer($item, $tracking_id, $transaction_id, $ip_address, $usernameServer, $passwordServer, $city_id, $credit, $uc)
    {
        try {
            // تنظیم پارامترهای کانکشن به صورت داینامیک
            $host = $ip_address;
            $port = '1433'; // پورت پیش‌فرض SQL Server
            $database = 'Ecity'; // نام دیتابیس
            $username = $usernameServer;
            $password = $passwordServer;

            // ایجاد نام کانکشن داینامیک
            $dynamicConnectionName = 'dynamic_sqlsrv_' . $city_id;

            // حذف کانکشن موجود با همین نام (اگر وجود داشته باشد)
            DB::purge($dynamicConnectionName);

            // تنظیم کانفیگ برای کانکشن داینامیک
            config([
                "database.connections.$dynamicConnectionName" => [
                    'driver' => 'sqlsrv',
                    'host' => $host,
                    'port' => $port,
                    'database' => $database,
                    'username' => $username,
                    'password' => $password,
                    'charset' => 'utf8',
                    'prefix' => '',
                    'prefix_indexes' => true,
                    'encrypt' => 'no',
                    'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'true')
                ],
            ]);

            $sql_srv = DB::connection($dynamicConnectionName)->table('ACardT')->select('*')->where('Mobile', Auth::user()->phone)->get();

            $card_id = $sql_srv[0]->Code;
            $sql_srv = DB::connection($dynamicConnectionName)->table('ACardT')->where('Code', $card_id)->update([
                'CardPrice' => $credit
            ]);


            $FKDevice = DB::connection($dynamicConnectionName)->table('ADeviceT')->where('Idnumber', 1)->get();

            $device_id = $FKDevice[0]->Idnumber;
            $FKPersonal = DB::connection($dynamicConnectionName)->table('PPersonelT')->where('Idnumber', 1)->get();
            $personel_id = $FKPersonal[0]->Idnumber;

            $op_type = 1;
            if ($item['isIncrease']) {
                $op = 2;
            }

            $InsertTransaction = DB::connection($dynamicConnectionName)->table('AIncDecEtebarT')->insert([
                'FKCard' => $card_id,
                'DateTime' => Carbon::now(),
                'Price' => $item['price'],
                'PreEtebar' => $item['preCredit'],
                'RemEtebar' => $item['afterCredit'],
                'FKADevice' => $device_id,
                'OP' => $op_type,
                'FKPersonel' => $personel_id,
                'Pay' => 0,
                'isValidRecord' => 0,
                'UC' => $uc,
                'PayCode' => null,
                'Cash' => 0,
                'RegDateTime' => Carbon::now(),
                'FKLine' => null,
                'LastOp' => null,
                'LastDeviçe' => null,
                'crc' => 1,
                'LastDevice' => null,
            ]);

        } catch (\Exception $e) {
            $item['tracking_id'] = $tracking_id;
            $item['transaction_id'] = $transaction_id;
            $item['user_id'] = Auth::user()->getAuthIdentifier();
            $item['credit'] = $credit;
            $item['uc'] = $uc;
            $JobFail = JobQueue::create([
                'job_type' => 'TRANSACTIONS',
                'ip_address' => $ip_address,
                'username' => $usernameServer,
                'password' => $passwordServer,
                'job_status' => 'PENDING',
                'json' => $item
            ]);
        }
    }

    function generateTransactionId()
    {
        // Generate a random string of 12 characters
        return rand(100000000000000, 999999999999999);
    }

    function generateTrackingId()
    {
        // Generate a random string of 16 characters
        return rand(1000000000, 9999999999);
    }

    public function generateRandomString($length = 10)
    {
        return substr(str_shuffle(str_repeat($x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length / strlen($x)))), 1, $length);
    }

    public function deleteUserTransactions()
    {
        $user = Auth::user()->getAuthIdentifier();
        $allTransactions = TransactionModel::where('user_id', $user)->get();
        if (count($allTransactions) > 0) {

            $deleteTransactions = TransactionModel::where('user_id', $user)->delete();
            if (!$deleteTransactions){
                return response()->json(['status'=>0, 'message'=>'حذف تراکنشات ناموفق بود']);
            }
            return response()->json(['status'=>1, 'message'=>'حذف تراکنشات باموفقیت انجام شد']);

        } else {
            return response()->json(['status'=>0, 'message'=>'تراکنشی جهت حذف وجود ندارد']);
        }
    }
    public function deleteAllTransactions()
    {
        $allTransactions = TransactionModel::get();
        if (count($allTransactions) > 0) {

            $deleteTransactions = TransactionModel::delete();
            if (!$deleteTransactions){
                return response()->json(['status'=>0, 'message'=>'حذف تراکنشات ناموفق بود']);
            }
            return response()->json(['status'=>1, 'message'=>'حذف تراکنشات باموفقیت انجام شد']);

        } else {
            return response()->json(['status'=>0, 'message'=>'تراکنشی جهت حذف وجود ندارد']);
        }
    }
}
