<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\WhmcsService;
use Illuminate\Support\Facades\Session;

class PostDataController extends Controller
{
    protected $whmcs;
    protected $authController;

    public function __construct(WhmcsService $whmcs, AuthController $authController)
    {
        $this->whmcs = $whmcs;
        $this->authController = $authController;
    }

    public function save(Request $request)
    {
        $action = $request->input('action');
        $actionbutton = $request->input('actionbutton');
        $serviceId = $request->input('serviceId');
        $selectuser = $request->input('selectuser');
        $username = $request->input('username');
        $displayname = $request->input('displayname');
        $password = $request->input('password');
        $mailboxsize = $request->input('mailboxsize');

        switch ($action) {
            case 'createsmartermailuser':
                return $this->createsmartermailuser($serviceId, $username, $displayname, $password, $mailboxsize);
            case 'savechangessmartermailuser':
                return $this->savechangessmartermailuser($serviceId, $selectuser, $username, $displayname, $password, $mailboxsize, $actionbutton);
            default:
                return response()->json(['status' => 'error', 'message' => 'Geçersiz işlem.']);
        }
    }

    protected function createsmartermailuser($serviceId, $username, $displayname, $password, $mailboxsize)
    {
      $response = $this->whmcs->createsmartermailuser($serviceId, $username, $displayname, $password, $mailboxsize);

      if ($response['result'] === 'success') {
        return response()->json(['success' => true, 'message' => 'Kullanıcı başarıyla oluşturuldu.']);
      } else {
        return response()->json(['success' => false, 'message' => $response['message'] ?? 'Bilinmeyen hata.']);
      }
    }

    protected function savechangessmartermailuser($serviceId, $selectuser, $username, $displayname, $password, $mailboxsize, $actionbutton)
    {
      if ($actionbutton == 'update') {
        $response = $this->whmcs->savechangessmartermailuser($serviceId, $selectuser, $username, $displayname, $password, $mailboxsize);

        if ($response['result'] === 'success') {
          return response()->json(['success' => true, 'message' => 'Kullanıcı bilgileri başarılı bir şekilde güncellenmiştir.']);
        } else {
          return response()->json(['success' => false, 'message' => $response['message'] ?? 'Bilinmeyen hata.']);
        }
      }

      if ($actionbutton == 'delete') {
        $response = $this->whmcs->deletesmartermailuser($serviceId, $selectuser);

        if ($response['result'] === 'success') {
          return response()->json(['success' => true, 'message' => 'Kullanıcı Silindi!']);
        } else {
          return response()->json(['success' => false, 'message' => $response['message'] ?? 'Bilinmeyen hata.']);
        }
      }
    }
}
