<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Website;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class AdminWebsiteManagementController extends Controller
{
    public function WebsiteManagement()
    {
        $website = Website::first();
        return view('adminDashboard.website-management', compact('website'));
    }

    public function UpdateWebsiteManagement(Request $request)
    {
        if (env('DEMO')) {
            Session::flash('message', 'You are not allowed to change password in demo mode.');
            Session::flash('alert-type', 'error');
            return redirect()->back();
        }

        $request->validate([
            'maintainance' => 'required',
            'sms_api' => 'required',
            'title' => 'required',
            'upi_id' => 'required',
            'notification' => 'required',
            'telegram' =>  'required'
        ]);
        $old_row = Website::first();
        if ($request->hasFile('qr_code')) {
            $old_row = Website::first();
            $old_row_img = public_path() . '/assets/img/' . $old_row->qr_code;
            if (is_file($old_row_img)) {
                unlink($old_row_img);
            }
            $image = $request->file('qr_code');
            $ext = $image->extension();
            $image_name = time() . uniqid() . '.' . $ext;
            request()->qr_code->move(public_path('assets/img/qr_code'), $image_name);
            $old_row->qr_code = 'qr_code/' . $image_name;
        }
        if ($request->hasFile('logo')) {
            $old_row = Website::first();
            $old_row_img = public_path() . $old_row->logo;
            if (is_file($old_row_img)) {
                unlink($old_row_img);
            }
            $image = $request->file('logo');
            $ext = $image->extension();
            $image_name = time() . uniqid() . '.' . $ext;
            request()->logo->move(public_path(), $image_name);
            $old_row->logo =  $image_name;
        }

        $old_row->maintainance = $request->maintainance;
        $old_row->online_gateway = $request->online_gateway;
        $old_row->sms_api = $request->sms_api;
        $old_row->upi_gateway_api = $request->upi_gateway_api;
        $old_row->title = $request->title;
        $old_row->upi_id = $request->upi_id;
        $old_row->notification = $request->notification;
        $old_row->telegram = $request->telegram;
        $old_row->save();

        Session::flash('message', 'Website Changes Saved Successfully.');
        Session::flash('alert-type', 'success');
        return redirect()->back();
    }
}
