<?php

namespace App\Http\Controllers;

use App\Models\Preference;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;

class TrialController extends Controller
{
    public function start(Request $request)
    {
        $user = Auth::user();

        if (
            $user->subscription_type === 'trial' &&
            $user->subscription_expiry_date &&
            now()->lte(\Carbon\Carbon::parse($user->subscription_expiry_date))
        ) {
            return response()->json(['message' => 'You already started your trial.'], 400);
        }


        $preference = Preference::first();
        $duration = (int) ($preference->subcription_duration_free ?? 3);

        $startDate = now();
        $expiryDate = $startDate->copy()->addMonths($duration);

        // Update the user subscription data
        $user->subscription_type = 'trial';
        $user->subscription_start_date = $startDate->format('Y-m-d');
        $user->subscription_expiry_date = $expiryDate->format('Y-m-d');
        $user->save();



        return response()->json([
            'message' => 'Trial started successfully!',
            'start' => $startDate->format('d-m-Y'),
            'expiry' => $expiryDate->format('d-m-Y'),
        ]);
    }


 public function cancel(Request $request)
{
    $user = Auth::user();

    // Step 1: Get the latest active subscription record
    $latestSubscription = DB::table('user_subscription')
        ->where('user_id', $user->id)
        ->orderByDesc('id')
        ->first();

    // Step 2: If found, update its end date to today
    if ($latestSubscription && Carbon::parse($latestSubscription->subscription_end)->isFuture()) {
        DB::table('user_subscription')
            ->where('id', $latestSubscription->id)
            ->update([
                'subscription_end' => Carbon::today(),
                 'modified_date' => now(),
            ]);
    }

    // Step 3: Update the user's current subscription status
    $user->subscription_type = 'free';
    $user->subscription_start_date = now();
    $user->subscription_expiry_date = null;
    $user->save();

    return redirect()->back()->with('success', 'Trial has been canceled.');
}

}
