<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use Illuminate\Support\Str;
use Carbon\Carbon;
use Stripe\StripeClient;


class AccountDeletionController extends Controller
{
    // Show the account deletion form
    public function showForm()
    {
        return view('account_deletion_form');
    }

    // Handle deletion request
    public function requestDeletion(Request $request)
{
    $request->validate([
        'email' => 'required|email|exists:users,email',
    ]);

    $user = User::where('email', $request->email)->first();

    $token = Str::random(60);

    DB::table('deletion_tokens')->insert([
        'email' => $user->email,
        'token' => Hash::make($token),
        'created_at' => now(),
    ]);

    Mail::send('emails.account_deletion_confirmation', ['token' => $token], function ($message) use ($user) {
        $message->to($user->email)
                ->subject('Confirm Account Deletion');
    });
    
    return back()->with('status', 'A confirmation email has been sent to your email address.');
}

    public function confirmDeletion($token)
{
    // Retrieve all valid tokens created within 24 hours
    $records = DB::table('deletion_tokens')
                ->where('created_at', '>=', Carbon::now()->subHours(24))
                ->get();

    // Search for a matching record
    $record = $records->first(function ($item) use ($token) {
        return Hash::check($token, $item->token);
    });

    // If no valid record is found
    if (!$record) {
        return redirect('/account-deletion')->with('error', 'Invalid or expired token.');
    }

    // Find the user
    $user = User::where('email', $record->email)->first();

    if (!$user) {
        return redirect('/account-deletion')->with('error', 'User not found.');
    }

    // Handle Stripe subscription cancellation if necessary
    if ($user->premium) {
        $stripe = new StripeClient(env('STRIPE_SECRET'));
        $stripe->subscriptions->cancel($user->subscription_id);
    }

    // Delete user-related data
    DB::table('users_ingredients')->where('user_id', $user->id)->delete();
    DB::table('subscriptions')->where('user_id', $user->id)->delete();
    DB::table('payments')->where('user_id', $user->id)->delete();

    // Delete the user
    $user->delete();

    // Delete the token
    DB::table('deletion_tokens')->where('email', $record->email)->delete();

    return response()->json([
            'message' => 'Your account has been successfully deleted.'], 200);
}
  public function apiRequestDeletion(Request $request)
{
    try {
        // Validate the incoming request
        $request->validate([
            'email' => 'required|email|exists:users,email',
        ]);

        $user = User::where('email', $request->email)->first();

        // Generate a secure token
        $token = Str::random(60);

        // Store the token in the database
        DB::table('deletion_tokens')->insert([
            'email' => $user->email,
            'token' => Hash::make($token),
            'created_at' => now(),
        ]);

        // Send confirmation email to the user
        Mail::send('emails.account_deletion_confirmation', ['token' => $token], function ($message) use ($user) {
            $message->to($user->email)
                    ->subject('Confirm Account Deletion');
        });

        // Return JSON response
        return response()->json([
            'message' => 'A confirmation email has been sent to your email address.'
        ], 200);
    } catch (\Exception $e) {
        // Log the error for debugging
        \Log::error('Error during account deletion request: ' . $e->getMessage());

        // Return JSON error response
        return response()->json([
            'error' => 'Something went wrong. Please try again later.',
        ], 500);
    }
}
}
