<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Pricing;
use App\Models\Notification;
use Illuminate\Http\Request;
use App\Models\Configuration;
use App\Models\MessageFromWebsite;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class WebsiteController extends Controller
{
    public function home(){
        $data['address'] = Configuration::where('key','=','address_configuration')->value('value');
        $data['phone'] = Configuration::where('key','=','phone_configuration')->value('value');
        $data['pricing'] = Pricing::where('status',1)->get();
        return view('website.index',$data);
    }

    public function contact(){
        $data['address'] = Configuration::where('key','=','address_configuration')->value('value');
        $data['phone'] = Configuration::where('key','=','phone_configuration')->value('value');
        $data['successMessage'] = session('successMessage');
        return view('website.contact',$data);
    }

    public function message_from_website(Request $request){
        $storeData = new MessageFromWebsite();
        $validation = $storeData->validate($request->all());
        if ($validation->fails()) {
            return redirect()->back()->withErrors($validation->errors())->withInput();
        }
        $storeData->fill($request->all());
        $storeData->save();
        $notifications = [];
        $users = DB::table('users')->where('is_superadmin', 1)->get();

        foreach ($users as $user) {
            $notifications[] = [
                'user_id' => $storeData->id,
                'send_to' => $user->id,
                'ticket_id' => $storeData->id,
                'title' => 'Contact Requst',
                'notification' => 'Conatact Request You. Visit Now..!!',
                'created_at' => date('Y-m-d H:i:s'),
                'link' => "/admin/contact_from_website/".$storeData->id,
            ];
        }

        Notification::insert($notifications);

        $successMessage = "We have received your message, we will contact you as soon as possible.";

        return redirect('/contact')->with('successMessage', $successMessage);
    }
    public function register(Request $request){
        $data['address'] = Configuration::where('key','=','address_configuration')->value('value');
        $data['phone'] = Configuration::where('key','=','phone_configuration')->value('value');
        $data['packages'] = Pricing::where('status', 1)->orderBy('price', 'asc')->get();
        $data['selectedPackageId'] = $request->query('package_id', null);
        $data['successMessage'] = session('successMessage');
        return view('website.register', $data);
    }

    public function registerStore(Request $request) {
        $validator = Validator::make($request->all(), [
            'name'           => 'required|string|max:191',
            'email'          => 'required|email|unique:users,email',
            'contact_number' => 'required|string|max:20',
            'username'       => 'required|string|max:100|unique:users,username',
            'password'       => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        DB::beginTransaction();
        try {
            $userData = new User();
            $userData->name = $request->input('name');
            $userData->email = $request->input('email');
            $userData->contact_number = $request->input('contact_number');
            $userData->phone = $request->input('contact_number');
            $userData->company_name = $request->input('company_name', $request->input('name') . ' Enterprise');
            $userData->address = $request->input('address', 'Dhaka, Bangladesh');
            $userData->nid = $request->input('nid');
            $userData->username = $request->input('username');
            $userData->password = Hash::make($request->input('password'));
            $userData->role_id = 1; // Standard User / Admin role
            $userData->status = 1; // Active
            $userData->api_key = bin2hex(random_bytes(32));
            $userData->masking_rate = 0.45;
            $userData->non_masking_rate = 0.25;
            $userData->save();

            $packageId = $request->input('package_id');
            $package = $packageId ? Pricing::find($packageId) : null;
            $trxId = $request->input('transaction_id');

            if ($package && $trxId) {
                // Manual / QR Code Payment Record
                $payment = new \App\Models\Payment();
                $payment->user_id = $userData->id;
                $payment->package_id = $package->id;
                $payment->request_amount = $package->price;
                $payment->approve_amount = $package->price;
                $payment->due_amount = 0;
                $payment->sender_types = 1;
                $payment->totalSMS = $package->sms_limit ?: 0;
                $payment->payement_type = 4; // Package purchase
                $payment->payement_method = $request->input('payment_method', 2); // 2: bKash, 4: Nagad, etc.
                $payment->phone = $request->input('sender_phone', $userData->contact_number);
                $payment->transaction_id = $trxId;
                $payment->date = now()->toDateString();
                $payment->status = 1; // Approved upon registration
                $payment->approved_at = now();
                $payment->approved_by = 1;
                $payment->notes = 'Registration Package Activation via QR Payment TrxID: ' . $trxId;
                $payment->save();

                // Activate Package
                \App\Services\PackageActivationService::activatePackage($userData->id, $package->id, $payment->id);
            }

            // Superadmin notification
            $notifications = [];
            $superAdmins = DB::table('users')->where('is_superadmin', 1)->get();
            foreach ($superAdmins as $admin) {
                $notifications[] = [
                    'user_id'     => $userData->id,
                    'send_to'     => $admin->id,
                    'ticket_id'   => $userData->id,
                    'title'       => $userData->name . ' Registered with Package',
                    'notification'=> 'New User Registration with ' . ($package ? $package->title : 'Standard Plan') . '. TrxID: ' . ($trxId ?: 'N/A'),
                    'created_at'  => now(),
                    'link'        => "/admin/users_details/" . $userData->id,
                ];
            }
            if (!empty($notifications)) {
                Notification::insert($notifications);
            }

            DB::commit();

            // Auto-login newly registered user
            auth()->login($userData);

            return redirect('/admin/dashboard')->with('successMessage', 'Account registered and package activated successfully! Welcome to SMS Gateway.');
        } catch (\Throwable $e) {
            DB::rollBack();
            return redirect()->back()->withErrors(['error' => 'Registration error: ' . $e->getMessage()])->withInput();
        }
    }

    public function packages(){
        $data['address'] = Configuration::where('key','=','address_configuration')->value('value');
        $data['phone'] = Configuration::where('key','=','phone_configuration')->value('value');
        $data['pricing'] = Pricing::where('status',1)->get();
        return view('website.packages',$data);
    }

    public function api_documentation(){
        $data['address'] = Configuration::where('key','=','address_configuration')->value('value');
        $data['phone'] = Configuration::where('key','=','phone_configuration')->value('value');

        return view('website.api_documentation',$data);
    }
}
