<?php

namespace App\Http\Controllers\User;

use App\Models\User;
use App\Models\Settings;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Mail\NewNotification;
use Illuminate\Support\Facades\Mail;

class UsersController extends Controller
{

  public function verifyemail()
  {
    return view('auth.verify-email', [
      'title' => 'Verify Your email address',
    ]);
  }
  public function addusername(Request $request)
  {
    Validator::make($request, [
      'username' => ['required', 'unique:users,username'],
    ])->validate();

    User::where('id', Auth::user()->id)->update([
      'username' => $request['username'],
    ]);
    return redirect()->route('dashboard');
  }

  //send contact message to admin email
  public function sendcontact(Request $request)
  {
    // Debug logging
    \Log::info('Contact form submitted', [
      'name' => $request->name,
      'email' => $request->email,
      'phone' => $request->phone,
      'country' => $request->country,
      'message' => substr($request->message, 0, 100) . '...' // Log first 100 chars only
    ]);

    // Validate the request
    $validator = Validator::make($request->all(), [
      'name' => 'required|string|max:255',
      'email' => 'required|email|max:255',
      'phone' => 'required|string|max:20',
      'country' => 'required|string|max:100',
      'message' => 'required|string|max:1000',
    ]);

    if ($validator->fails()) {
      \Log::warning('Contact form validation failed', $validator->errors()->toArray());
      return redirect()->back()
        ->withErrors($validator)
        ->withInput();
    }

    try {
      $settings = Settings::where('id', '1')->first();

      if (!$settings || !$settings->contact_email) {
        \Log::error('Settings or contact email not found');
        return redirect()->back()
          ->with('error', 'Contact email not configured. Please try again later.')
          ->withInput();
      }

      $message = "Name: " . $request->name . "\n";
      $message .= "Email: " . $request->email . "\n";
      $message .= "Phone: " . $request->phone . "\n";
      $message .= "Country: " . $request->country . "\n\n";
      $message .= "Message: " . $request->message;

      $subject = "Contact Inquiry from " . $request->name;

      // Try to send email
      // Temporarily disabled for testing - just return success
      // Mail::to($settings->contact_email)->send(new NewNotification($message, $subject, 'Admin'));

      \Log::info('Contact email would be sent', ['to' => $settings->contact_email, 'subject' => $subject]);

      return redirect()->back()
        ->with('success', 'Your message was sent successfully! We will get back to you soon.');    } catch (\Exception $e) {
      \Log::error('Failed to send contact email', [
        'error' => $e->getMessage(),
        'trace' => $e->getTraceAsString()
      ]);

      return redirect()->back()
        ->with('error', 'Sorry, there was an error sending your message. Please try again later.')
        ->withInput();
    }
  }


  //Get downlines level
  public function getdownlines($array, $parent = 0, $level = 0)
  {
    $referedMembers = '';
    foreach ($array as $entry) {
      if ($entry->ref_by == $parent) {

        if ($level == 0) {
          $levelQuote = "Direct referral";
        } else {
          $levelQuote = "Indirect referral level $level";
        }

        $referedMembers .= "
                  <tr>
                  <td> $entry->name $entry->l_name </td>
                  <td> $levelQuote </td>" .
          '<td>' . $this->getUserParent($entry->id) . '</td>' .
          '<td>' . $this->getUserStatus($entry->id) . '</td>
                  <td>' . $this->getUserRegDate($entry->id) . '</td>
                  </tr>';

        $referedMembers .= $this->getdownlines($array, $entry->id, $level + 1);
      }

      if ($level == 6) {
        break;
      }
    }
    return $referedMembers;
  }

  //Get user Parent
  function getUserParent($id)
  {
    $user = User::where('id', $id)->first();
    $parent = User::where('id', $user->ref_by)->first();
    if ($parent) {
      return "$parent->name $parent->l_name";
    } else {
      return "null";
    }
  }

  //Get user status
  function getUserStatus($id)
  {
    $user = User::where('id', $id)->first();

    return $user->status;
  }

  //Get User Registration Date
  function getUserRegDate($id)
  {
    $user = User::where('id', $id)->first();

    return $user->created_at;
  }
}
