<?php

namespace App\Console\Commands;

use App\Services\Accounting\AccountingSyncService;
use App\Models\Hotel;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class SyncAccountingData extends Command
{
    protected $signature = 'accounting:sync {hotel_id?} {--module=all}';
    protected $description = 'Sync all operational data to accounting';

    protected $syncService;

    public function __construct(AccountingSyncService $syncService)
    {
        parent::__construct();
        $this->syncService = $syncService;
    }

    public function handle()
    {
        $hotelId = $this->argument('hotel_id');
        $module = $this->option('module');

        $hotels = $hotelId 
            ? [Hotel::find($hotelId)]
            : Hotel::where('status', 'active')->get();

        foreach ($hotels as $hotel) {
            if (!$hotel) continue;

            $this->info("Syncing data for hotel: {$hotel->name}");

            if ($module === 'all') {
                $result = $this->syncService->syncAll($hotel->id);
            } else {
                $method = 'sync' . ucfirst($module);
                if (method_exists($this->syncService, $method)) {
                    $result = $this->syncService->$method($hotel->id);
                } else {
                    $this->error("Invalid module: {$module}");
                    return 1;
                }
            }

            if ($result['success']) {
                $this->info($result['message']);
                foreach ($result['results'] ?? [$result] as $moduleResult) {
                    if (isset($moduleResult['synced_count'])) {
                        $this->line("  - {$moduleResult['module']}: {$moduleResult['synced_count']} records");
                    }
                }
            } else {
                $this->error("Failed to sync: " . ($result['message'] ?? 'Unknown error'));
                foreach ($result['errors'] ?? [] as $error) {
                    $this->error("  - {$error}");
                }
            }
        }

        return 0;
    }
}