<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\WhmcsService;

class SyncWhmcsInvoices extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'whmcs:sync-invoices';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sync invoices from WHMCS to local accounting';

    /**
     * Execute the console command.
     */
    public function handle(WhmcsService $whmcs)
    {
        $this->info('Starting WHMCS Invoice Sync...');

        $result = $whmcs->syncAllInvoices();

        if ($result['success']) {
            $this->success("Successfully synced {$result['synced']} invoices.");

            if (!empty($result['errors'])) {
                $this->warn('Encountered ' . count($result['errors']) . ' errors:');
                foreach ($result['errors'] as $error) {
                    $this->error($error);
                }
            }
        } else {
            $this->error('Failed to sync invoices: ' . $result['message']);
        }

        return 0;
    }
}
