<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Post;
use App\Models\PostPlatform;
use App\Models\SocialAccount;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class PostController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'brand_id' => 'required|exists:brands,id',
            'content' => 'required',
        ]);

        $post = Post::create([
            'user_id' => auth()->id(),
            'brand_id' => $request->brand_id,
            'content' => $request->input('content'),
            'status' => 'draft',
        ]);

        return response()->json([
            'status' => true,
            'message' => 'Post created successfully.',
            'data' => $post,
        ]);
    }

    public function publish(Post $post)
    {
        try {
            $accounts = SocialAccount::where(
                'brand_id',
                $post->brand_id
            )
                ->where('provider', 'facebook')
                ->get();

            $results = [];

            foreach ($accounts as $account) {
                $response = Http::post(
                    "https://graph.facebook.com/v23.0/{$account->account_id}/feed",
                    [
                        'message' => $post->content,
                        'access_token' => $account->access_token,
                    ]
                );

                $facebook = $response->json();

                if (isset($facebook['id'])) {
                    $res = PostPlatform::create([
                        'post_id' => $post->id,
                        'social_account_id' => $account->id,
                        'provider_post_id' => $facebook['id'],
                        'status' => 'published',
                        'response' => json_encode($facebook),
                    ]);

                    $results[] = $facebook;
                } else {
                    $res = PostPlatform::create([
                        'post_id' => $post->id,
                        'social_account_id' => $account->id,
                        'status' => 'failed',
                        'response' => json_encode($facebook),
                    ]);

                    $results[] = $facebook;
                }
                $postPlatforms[] = [
                    'post_platform_id' => $res->id,
                    'social_account_id' => $account->id,
                ];
            }

            $post->update([
                'status' => 'published'
            ]);

            return response()->json([
                'status' => true,
                'message' => 'Post published successfully.',
                'data' => $results,
                'platforms' => $postPlatforms,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => $e->getMessage(),
            ], 500);
        }
    }

    public function schedule(Request $request, Post $post)
    {
        $request->validate([
            'scheduled_at' => 'required|date|after:now',
        ]);

        $post->update([
            'scheduled_at' => $request->scheduled_at,
            'status' => 'scheduled',
        ]);

        return response()->json([
            'status' => true,
            'message' => 'Post scheduled successfully',
            'data' => $post,
        ]);
    }

    public function publishImage(Request $request, Post $post)
    {
        $request->validate([
            'image_url' => 'required|url',
        ]);

        $account = SocialAccount::where('brand_id', $post->brand_id)
            ->where('provider', 'facebook')
            ->first();

        $response = Http::post(
            "https://graph.facebook.com/v23.0/{$account->account_id}/photos",
            [
                'url' => $request->image_url,
                'caption' => $post->content,
                'access_token' => $account->access_token,
            ]
        );

        return $response->json();
    }
}
