<?php

namespace App\Http\Controllers\User;

use App\Models\User;
use App\Models\Settings;
use App\Models\ContactMessage;
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;
use Illuminate\Support\Facades\Log;

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)
  {
    // Validate the form data
    $validator = Validator::make($request->all(), [
      'fname' => 'required|string|max:255',
      'email' => 'required|email|max:255',
      'subject' => 'required|string|max:255',
      'phone' => 'required|string|max:20',
      'service_branch' => 'nullable|string|max:255',
      'rank' => 'nullable|string|max:255',
      'military_status' => 'nullable|string|max:255',
      'departure_city' => 'nullable|string|max:255',
      'destination_city' => 'nullable|string|max:255',
      'departure_date' => 'nullable|date',
      'return_date' => 'nullable|date|after_or_equal:departure_date',
      'passengers' => 'nullable|string|max:20',
      'trip_type' => 'nullable|string|max:255',
      'payment_preference' => 'nullable|string|max:255',
      'message' => 'required|string|max:5000',
    ]);

    if ($validator->fails()) {
      return redirect()->back()
        ->withErrors($validator)
        ->withInput();
    }

    try {
      // Save to database
      $contactMessage = ContactMessage::create([
        'fname' => $request->fname,
        'email' => $request->email,
        'subject' => $request->subject,
        'phone' => $request->phone,
        'service_branch' => $request->service_branch,
        'rank' => $request->rank,
        'military_status' => $request->military_status,
        'departure_city' => $request->departure_city,
        'destination_city' => $request->destination_city,
        'departure_date' => $request->departure_date,
        'return_date' => $request->return_date,
        'passengers' => $request->passengers,
        'trip_type' => $request->trip_type,
        'payment_preference' => $request->payment_preference,
        'message' => $request->message,
        'status' => 'unread'
      ]);

      // Get settings for email
      $settings = Settings::where('id', '1')->first();

      // Prepare email content
      $isFlightBooking = strpos(strtolower($request->subject), 'flight') !== false;

      $emailMessage = "
        <h3>New " . ($isFlightBooking ? 'Flight Booking Request' : 'Contact Message') . " from Military Personnel</h3>
        <div style='border: 2px solid #2d4a1e; padding: 20px; margin: 10px 0; background-color: #f8f9fa;'>
          <h4 style='color: #2d4a1e; margin-top: 0;'>Personal Information</h4>
          <p><strong>Name:</strong> {$request->fname}</p>
          <p><strong>Email:</strong> {$request->email}</p>
          <p><strong>Phone:</strong> {$request->phone}</p>
          <p><strong>Subject:</strong> {$request->subject}</p>";

      if ($request->service_branch) {
        $emailMessage .= "<p><strong>Service Branch:</strong> {$request->service_branch}</p>";
      }

      if ($request->rank) {
        $emailMessage .= "<p><strong>Rank/Grade:</strong> {$request->rank}</p>";
      }

      if ($request->military_status) {
        $emailMessage .= "<p><strong>Military Status:</strong> {$request->military_status}</p>";
      }

      $emailMessage .= "</div>";

      // Add flight booking details if present
      if ($isFlightBooking && ($request->departure_city || $request->destination_city || $request->departure_date)) {
        $emailMessage .= "
          <div style='border: 2px solid #d97706; padding: 20px; margin: 10px 0; background-color: #fff7ed;'>
            <h4 style='color: #d97706; margin-top: 0;'>✈️ Flight Details</h4>";

        if ($request->departure_city) {
          $emailMessage .= "<p><strong>Departure City:</strong> {$request->departure_city}</p>";
        }

        if ($request->destination_city) {
          $emailMessage .= "<p><strong>Destination City:</strong> {$request->destination_city}</p>";
        }

        if ($request->departure_date) {
          $emailMessage .= "<p><strong>Departure Date:</strong> " . date('F j, Y', strtotime($request->departure_date)) . "</p>";
        }

        if ($request->return_date) {
          $emailMessage .= "<p><strong>Return Date:</strong> " . date('F j, Y', strtotime($request->return_date)) . "</p>";
        }

        if ($request->passengers) {
          $emailMessage .= "<p><strong>Number of Passengers:</strong> {$request->passengers}</p>";
        }

        if ($request->trip_type) {
          $emailMessage .= "<p><strong>Trip Type:</strong> {$request->trip_type}</p>";
        }

        if ($request->payment_preference) {
          $emailMessage .= "<p><strong>Payment Preference:</strong> {$request->payment_preference}</p>";
        }

        $emailMessage .= "</div>";
      }

      $emailMessage .= "
        <div style='border: 2px solid #6b7280; padding: 20px; margin: 10px 0; background-color: #f9fafb;'>
          <h4 style='color: #374151; margin-top: 0;'>💬 Message Details</h4>
          <p style='background-color: white; padding: 15px; border-radius: 5px; border-left: 4px solid #2d4a1e;'>{$request->message}</p>
        </div>
        <hr style='border: 1px solid #e5e7eb; margin: 20px 0;'>
        <div style='background-color: #f3f4f6; padding: 15px; border-radius: 5px; text-align: center;'>
          <p style='margin: 0; font-size: 12px; color: #6b7280;'>
            <strong>Message ID:</strong> {$contactMessage->id} |
            <strong>Received:</strong> " . now()->format('F j, Y \a\t g:i A') . " |
            <strong>Priority:</strong> " . ($isFlightBooking ? 'HIGH (Flight Booking)' : 'NORMAL') . "
          </p>
        </div>
      ";

      $subject = ($isFlightBooking ? "🛩️ FLIGHT BOOKING REQUEST" : "📧 Military Contact Inquiry") . ": {$request->subject} - from {$request->fname}";

      // Send email to admin (don't fail if email doesn't send)
      try {
        Mail::to($settings->contact_email)->send(new NewNotification($emailMessage, $subject, 'Admin'));
      } catch (\Exception $emailError) {
        // Log email error but don't fail the entire process
        Log::error('Contact form email sending failed', [
          'error_message' => $emailError->getMessage(),
          'user_email' => $request->email,
          'user_name' => $request->fname,
          'contact_message_id' => $contactMessage->id,
          'timestamp' => now()->toDateTimeString()
        ]);
      }

      $successMessage = $isFlightBooking
        ? '✈️ Mission accomplished! Your flight booking request has been transmitted to Military Travel Command. Expect a response within 24 hours with available options and pricing.'
        : '📧 Mission accomplished! Your secure message has been transmitted to Command Center. Expect a response within 24 hours.';

      return redirect()->back()
        ->with('success', $successMessage);

    } catch (\Exception $e) {
      // Log database errors only (critical errors)
      Log::error('Contact form database error', [
        'error_message' => $e->getMessage(),
        'error_file' => $e->getFile(),
        'error_line' => $e->getLine(),
        'user_email' => $request->email ?? 'unknown',
        'user_name' => $request->fname ?? 'unknown',
        'subject' => $request->subject ?? 'unknown',
        'timestamp' => now()->toDateTimeString(),
        'trace' => $e->getTraceAsString()
      ]);

      return redirect()->back()
        ->with('error', 'Communication error occurred. Please try again or contact emergency hotline.')
        ->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;
  }
}
