<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class PostsScheduleCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'posts:schedule';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Process scheduled social media posts';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        try {
            $this->info('Processing scheduled posts...');
            
            // Get scheduled posts that are ready to be published
            $scheduledPosts = DB::table('social_posts')
                ->where('status', 3) // PostStatus::SCHEDULE = 3
                ->where('schedule_time', '<=', now())
                ->where('is_scheduled', true)
                ->get();

            $processedCount = 0;
            
            foreach ($scheduledPosts as $post) {
                // Update post status to published
                DB::table('social_posts')
                    ->where('id', $post->id)
                    ->update([
                        'status' => 1, // PostStatus::SUCCESS = 1
                        'posted_at' => now(),
                        'updated_at' => now()
                    ]);
                
                $processedCount++;
                $this->info("Published post ID: {$post->id}");
            }

            $message = "Processed {$processedCount} scheduled posts";
            $this->info($message);
            Log::info($message);

            return Command::SUCCESS;
            
        } catch (\Exception $e) {
            $error = 'Error processing scheduled posts: ' . $e->getMessage();
            $this->error($error);
            Log::error($error);
            return Command::FAILURE;
        }
    }
}