<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use GuzzleHttp\Client;
use Illuminate\Support\Facades\Session;
use Carbon\Carbon;

class SubscriptionPlanController extends Controller
{
    public function create()
    {
        return view('awa.pages.subscription-form', ['plan'=> null]);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'plan_name'     => 'required|string|max:255',
            'duration_days' => 'required|integer|min:1',
            'price'         => 'required|numeric|min:0',
            'features'      => 'required|array|min:1',
            'features.*'    => 'required|string|max:255',
        ]);
    
        $client = new Client([
            'base_uri' => config('services.admin_api.base_url'),
            'timeout'  => 5,
        ]);
    
       
        $multipart = [
            ['name'=>'plan_name',     'contents'=>$data['plan_name']],
            ['name'=>'duration_days', 'contents'=> (string) $data['duration_days']],
            ['name'=>'price',         'contents'=> (string) $data['price']],
        ];
    
        foreach ($data['features'] as $feature) {
            $multipart[] = [
                'name'     => 'features',
                'contents' => $feature,
            ];
        }
    
        try {
            $resp = $client->post('/admin/manage_subscription_plan/', [
                'multipart' => $multipart,
            ]);
    
            $body = json_decode((string)$resp->getBody(), true);
    
            if (($body['status'] ?? 0) === 1) {
                return redirect()
                    ->route('subscription.create')
                    ->with('success', $body['message']);
            }
    
            return back()
                ->withErrors(['form' => $body['message'] ?? 'Unknown error'])
                ->withInput();
    
        } catch (\Exception $e) {
            return back()
                ->withErrors(['form' => 'Service unavailable.'])
                ->withInput();
        }
    }


    public function index(Request $request)
    {
        $client = new Client([
            'base_uri' => config('services.admin_api.base_url'),
            'timeout'  => 5,
        ]);

        try {
            $response = $client->get('/get_subscription_plans');
            $body     = json_decode($response->getBody(), true);
            $plans    = $body['plans'] ?? [];
            
        } catch (\Exception $e) {
            // flash a brief error, fall back to empty
            return back()->with('error', 'Unable to fetch subscription plans.');
        }

        return view('awa.pages.subscriptions', compact('plans'));
    }



    public function edit(string $plan_name)
    {
        $client = new Client([
            'base_uri' => config('services.admin_api.base_url'),
            'timeout'  => 5,
        ]);

        try {
            $resp = $client->get('/get_subscription_plans');
            $body = json_decode((string)$resp->getBody(), true);
            $plan = collect($body['plans'] ?? [])
                ->first(fn($p)=> $p['plan_name'] === $plan_name);
        } catch(\Exception $e){
            $plan = null;
        }

        if (! $plan) {
            return redirect()->route('admin.subscriptions')
                             ->with('error','Plan not found');
        }

        $plan['features'] = $plan['features'] ?? [];
        return view('awa.pages.subscription-form', compact('plan'));
    }

    
    
    public function update(Request $request, string $plan_name)
{
    $data = $request->validate([
        'duration_days' => 'required|integer|min:1',
        'price'         => 'required|numeric|min:0',
        'features'      => 'required|array|min:1',
        'features.*'    => 'required|string|max:255',
    ]);

    $client = new Client([
        'base_uri' => config('services.admin_api.base_url'),
        'timeout'  => 5,
    ]);

   
    $formParams = [
        'plan_name' => $plan_name,
        'duration_days' => (string) $data['duration_days'],
        'price'         => (string) $data['price'],
       'features'      => $data['features'],
    ];

    try {
        $response = $client->post('/admin_update_subscription_plan/', [
            'form_params' => $formParams,
        ]);

        $body = json_decode((string) $response->getBody(), true);

        return redirect()
            ->route('admin.subscriptions')
            ->with('success', $body['message'] ?? 'Subscription plan updated.');
    } catch (\Exception $e) {
        return back()
            ->withErrors(['form' => 'Service unavailable.'])
            ->withInput();
    }
}
    





    public function destroy(string $plan_name)
    {
        $client = new Client([
            'base_uri' => config('services.admin_api.base_url'),
            'timeout'  => 5,
        ]);
    
        try {
            $res = $client->delete('/admin/delete_subscription_plan/', [
                'query' => ['plan_name' => $plan_name],
            ]);
    
            $body = json_decode((string)$res->getBody(), true);
    
            return redirect()
                ->route('admin.subscriptions')
                ->with('success', $body['message'] ?? 'Deleted');
        } catch (\Exception $e) {
            // you can log $e->getMessage() here if you want
            return back()->with('error', 'Service unavailable');
        }
    }



    public function subscribedUsers(Request $request)
    {
        $client = new Client([
            'base_uri' => config('services.admin_api.base_url'),
            'timeout'  => 5,
        ]);

        try {
            $resp = $client->get('/admin_get_subscription_user/');
            $body = json_decode((string)$resp->getBody(), true);
            
            $users = $body['subscribed_users'] ?? [];
        } catch (\Exception $e) {
            return back()->with('error', 'Unable to fetch subscribed users.');
        }

       
        foreach ($users as &$u) {
            $u['last_updated'] = \Carbon\Carbon::parse($u['last_updated'])
                                      ->setTimezone('Asia/Kolkata');
        }

        return view('awa.pages.subscribed-users', compact('users'));
    }



    public function transactions(Request $request)
    {
        $client = new Client([
            'base_uri' => config('services.admin_api.base_url'),
            'timeout'  => 5,
        ]);

        try {
            $resp = $client->get('/admin_get_transactions_history/');
            $body = json_decode((string)$resp->getBody(), true);
            $txns = $body['transactions'] ?? [];
        } catch (\Exception $e) {
            return back()->with('error', 'Unable to fetch transactions.');
        }

       
        foreach ($txns as &$t) {
            $t['last_updated'] = isset($t['last_updated'])
                ? Carbon::parse($t['last_updated'])->setTimezone('Asia/Kolkata')
                : null;
        }

        return view('awa.pages.transactions', ['transactions' => $txns]);
    }


}
