<?php

namespace App\Http\Controllers;

use App\Models\Settings;
use Illuminate\Http\Request;

class SettingsController extends Controller
{
    public function index() {
        $settings = Settings::first();
        $provider = json_decode($settings->sms_provider);
        $templates = json_decode($settings->template);
        return view("admin.settings.index", compact("provider", "templates"));
    }

    public function store(Request $request) {
        $request->validate([
            "provider" => ["required", "string", "url"],
            "key" => ["required"],
            "value" => ["required"],
        ]);

        $data = [
            "provider" => $request->provider,
            "phone" => $request->value[0],
            "message" => $request->value[1],
        ];
        $extra = [];
        foreach($request->key as $key => $name) {
            if($name != "phone" || $name != "message") {
                $extra[$name] = $request->value[$key];
            }            
        }
        $data["extra"] = $extra;
        $settings = Settings::first();
        $settings->sms_provider = json_encode($data);
        $settings->save();
        return redirect()->back()->with("message", "SMS Provider saved!");
    }

    public function invoiceSmsTemplate(Request $request) {
        $request->validate([
            "template" => ["required"],
        ]);

        $settings = Settings::first();
        $settings->template = json_encode([
            "invoice_template" => $request->template,
        ]);
        $settings->save();
        return redirect()->back()->with("message", "Invoice template saved!");
    }
}
