<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\CompanySetting;

use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;

class ProfileController extends Controller
{
    public function __construct()
    {
        // Ensure the user is authenticated for all actions in this controller
        $this->middleware('auth:sanctum');
    }

    // Function to get the user's profile
    public function show()
    {
        $user = Auth::user();
        return response()->json([
            'status' => true,
            'message' => 'User profile retrieved successfully',
            'data' => $user->only(['id', 'FirstName', 'SurName', 'Username', 'email']),
        ], 200);
    }

    // Function to update the user's profile
    public function update(Request $request)
    {
        $user = Auth::user();

        // dd($user);
        // Validate the request data
        $validator = Validator::make($request->all(), [
            'FirstName' => 'required|string|max:255',
            'ContactNo' => 'required|string|max:255',
            // 'SurName' => 'required|string|max:255',
            // 'Username' => 'required|string|max:255|unique:users,Username,' . $user->id,
            'email' => 'required|string|email|max:255|unique:users,email,' . $user->id,
        ]);


        if ($validator->fails()) {
            $errors = $validator->errors()->all();

            return response()->json([
                'status' => false,
                // 'message' => 'Validation failed',
                'message' => implode(' ', $errors),
            ], 200);
        }

        // Check if validation fails
        // if ($validator->fails()) {
        //     return response()->json([
        //         'status' => false,
        //         // 'message' => 'Validation Error',
        //         'message' => $validator->errors(),
        //     ], 200);
        // }

        // Update the user's profile
        // $user->update($request->only(['FirstName', 'SurName', 'Username', 'email']));

        // Update user data
        $user->FirstName = $request->FirstName;
        $user->SurName = $request->SurName;
        $user->HouseName = $request->HouseName;
        $user->StreetNo = $request->StreetNo;
        $user->StreetName = $request->StreetName;
        $user->Town = $request->Town;
        $user->Area = $request->Area;
        $user->County = $request->County;
        $user->PostCode = $request->PostCode;
        $user->ContactNo = $request->ContactNo;
        $user->email = $request->email;

        $user->save();


        // Prepare the response data
        $userData = $user->only(['id', 'FirstName', 'SurName', 'Username', 'email']);
        $userData = array_map(function ($value) {
            return $value === null ? '' : $value;
        }, $userData);

        return response()->json([
            'status' => true,
            'message' => 'Profile updated successfully',
            'data' => $userData,
        ], 200);


        // return response()->json([
        //     'status' => true,
        //     'message' => 'Profile updated successfully',
        //     'data' => $user->only(['id', 'FirstName', 'SurName', 'Username', 'email']),
        // ], 200);
    }

    public function deleteAccount(Request $request)
    {
        $user = auth()->user();

        // Soft delete the account by setting the deactivated_at field
        // $user->deactivated_at = Carbon::now();
        // $user->save();


        $companySettings = CompanySetting::find(1);
        // dd($companySettings->EmailAddress);
        $send = $this->sendAccountDeleteEmail($user, $companySettings);

        if ($send) {
            $user->delete();
            // Optionally revoke all tokens
            $user->tokens()->delete();

            return response()->json([
                'status' => true,
                'message' => 'Account successfully deleted.',
            ], 200);
        }
    }


    private function sendAccountDeleteEmail($user, $companySettings)
    {

        $mail = new PHPMailer(true);

        try {

            $mail->isMail();

            //Recipients
            $mail->setFrom($companySettings->EmailAddress, $companySettings->Name);
            $mail->addAddress($user->email);
            $mail->addBCC($companySettings->EmailAddress);

            //Content
            $mail->isHTML(true);
            //Set email format to HTML
            $mail->Subject = 'Account Successfully Deleted.';

            $mail->Body = "
                <html>
                    <head>
                        <style>
                            table {
                                border-collapse: collapse;
                                width: 100%;
                            }

                            th, td {
                                border: 1px solid #dddddd;
                                text-align: left;
                                padding: 8px;
                            }

                            th {
                                background-color: #f2f2f2;
                            }
                        </style>
                    </head>
                    <body>
                        <p>Dear " . $user->FirstName . "</p>

                        <p>We wanted to confirm that your account with username <b>" . $user->Username . "</b> has been successfully deleted. We're sorry to see you go, but we respect your decision and appreciate the time you spent with us.</p>

                        <p>If you ever wish to return, we'll be here to welcome you back. Should you have any feedback or questions, feel free to reach out to us at " . $companySettings->EmailAddress . ".</p>

                        <p>Thank you for being a part of our community.</p>

                        <p>Kind regards,<br>
                        The Evolution App Team.</p>
                    </body>
                </html>";

            $send = $mail->send();
            return $send;
            // dd($send);

        } catch (Exception $e) {
            return response()->json([
                'status' => false,
                'message' => 'Failed to send the account deletion email',
                'error' => $e->getMessage()
            ], 200);
        }
    }
}
