<?php

namespace App\Http\Controllers\Accounting;

use App\Http\Controllers\Controller;
use App\Services\WhmcsService;
use Illuminate\Http\Request;
use App\Models\Setting;

class WhmcsSyncController extends Controller
{
    protected $whmcs;

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

    /**
     * Display the sync dashboard.
     */
    public function index()
    {
        $isConfigured = $this->whmcs->isConfigured();
        $lastSync = Setting::getValue('whmcs', 'last_sync_at', 'Never');

        return view('accounting.whmcs.index', compact('isConfigured', 'lastSync'));
    }

    /**
     * Sync clients from WHMCS.
     */
    public function syncClients()
    {
        $result = $this->whmcs->syncAllClients();

        if ($result['success']) {
            Setting::setValue('whmcs', 'last_sync_at', now()->toDateTimeString());
            return back()->with('success', "Successfully synced {$result['synced']} clients from WHMCS.");
        }

        return back()->with('error', "Sync failed: " . ($result['message'] ?? 'Unknown error'));
    }

    /**
     * Sync invoices from WHMCS.
     */
    public function syncInvoices()
    {
        $result = $this->whmcs->syncAllInvoices();

        if ($result['success']) {
            Setting::setValue('whmcs', 'last_sync_at', now()->toDateTimeString());
            return back()->with('success', "Successfully synced {$result['synced']} invoices from WHMCS.");
        }

        return back()->with('error', "Sync failed: " . ($result['message'] ?? 'Unknown error'));
    }

    /**
     * Sync licenses from WHMCS.
     */
    public function syncLicenses()
    {
        $result = $this->whmcs->syncAllLicenses();

        if ($result['success']) {
            Setting::setValue('whmcs', 'last_sync_at', now()->toDateTimeString());
            return back()->with('success', "Successfully synced {$result['synced']} licenses from WHMCS.");
        }

        return back()->with('error', "Sync failed: " . ($result['message'] ?? 'Unknown error'));
    }
    /**
     * Sync subscriptions (services) from WHMCS.
     */
    public function syncSubscriptions()
    {
        $result = $this->whmcs->syncAllSubscriptions();

        if ($result['success']) {
            Setting::setValue('whmcs', 'last_sync_at', now()->toDateTimeString());
            return back()->with('success', "Successfully synced {$result['synced']} subscriptions from WHMCS.");
        }

        return back()->with('error', "Sync failed: " . ($result['message'] ?? 'Unknown error'));
    }
}
