<?php

namespace App\Http\Controllers\Legacy;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use App\Services\AvatarService;
use Carbon\Carbon;

class UserController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();
        if (! $user) {
            abort(403);
        }

        // Handle profile update
        if ($request->isMethod('post')) {
            $action = $request->input('confirm');

            if ($action === 'true_password') {
                $old = $request->input('oldpass');
                $new = $request->input('newpass');
                $new2 = $request->input('newpass2');

                if ($new && $new === $new2 && Hash::check($old, $user->password)) {
                    $user->password = Hash::make($new);
                    $user->save();
                    $request->session()->flash('status', 'Password changed.');
                } else {
                    $request->session()->flash('error', 'Password not changed.');
                }
            } else {
                // Map legacy form fields into the modern schema.
                $data = $request->only(['name','web','country_code','signature','description','about_me']);

                // Core user column: `name`
                if (isset($data['name'])) {
                    $user->name = $data['name'] ?? $user->name;
                }

                // Collect other profile updates to persist into `user_profiles` when available
                $profileUpdates = [];
                if (!empty($data['web'])) $profileUpdates['website'] = $data['web'];
                if (!empty($data['signature'])) $profileUpdates['signature'] = $data['signature'];
                if (!empty($data['description'])) $profileUpdates['description'] = $data['description'];
                if (!empty($data['about_me'])) $profileUpdates['about'] = $data['about_me'];
                if (!empty($data['country_code'])) $profileUpdates['country_code'] = $data['country_code'];

                $d1 = $request->input('date1');
                $d2 = $request->input('date2');
                $d3 = $request->input('date3');
                if ($d1 && $d2 && $d3) {
                    $profileUpdates['birthdate'] = sprintf('%04d-%02d-%02d', (int)$d3, (int)$d2, (int)$d1);
                }

                $userGender = $request->input('gender', $user->gender);
                if (!empty($userGender)) {
                    $g = strtolower($userGender);
                    $map = ['m' => 'M', 'f' => 'F', 'n' => 'X', 'x' => 'X'];
                    $profileUpdates['gender'] = $map[$g] ?? strtoupper($userGender);
                }

                $profileUpdates['mlist'] = $request->has('newsletter') ? 1 : 0;
                $profileUpdates['friend_upload_notice'] = $request->has('friend_upload_notice') ? 1 : 0;

                // Files: avatar/photo/emoticon
                if ($request->hasFile('avatar')) {
                    try {
                        $hash = app(AvatarService::class)->storeFromUploadedFile((int) $user->id, $request->file('avatar'));
                        $user->icon = $hash;
                    } catch (\Throwable $e) {
                        $request->session()->flash('error', 'Avatar upload failed.');
                    }
                }

                if ($request->hasFile('personal_picture')) {
                    $f = $request->file('personal_picture');
                    $name = $user->id . '.' . $f->getClientOriginalExtension();
                    $f->move(public_path('user-picture'), $name);
                    $profileUpdates['cover_image'] = $name;
                    $user->picture = $name;
                }

                if ($request->hasFile('emotion_icon')) {
                    $f = $request->file('emotion_icon');
                    $name = $user->id . '.' . $f->getClientOriginalExtension();
                    $f->move(public_path('emotion'), $name);
                    $user->eicon = $name;
                }

                // Save core user fields
                $user->save();

                // Persist profile updates into `user_profiles` when available, otherwise fallback to `users` table
                try {
                    if (!empty($profileUpdates) && Schema::hasTable('user_profiles')) {
                        DB::table('user_profiles')->updateOrInsert(['user_id' => $user->id], $profileUpdates + ['updated_at' => now(), 'created_at' => now()]);
                    } elseif (!empty($profileUpdates)) {
                        DB::table('users')->where('id', $user->id)->update($profileUpdates);
                    }
                } catch (\Throwable $e) {
                    // ignore persistence errors for legacy path
                }

                $request->session()->flash('status', 'Profile updated.');
            }
        }

        // Prepare birth date parts for the legacy form (initialized — parsed after merging profiles)
        $birthDay = null;
        $birthMonth = null;
        $birthYear = null;

        // Load country list if available (legacy table names)
        $countries = collect();
        try {
            if (Schema::hasTable('country_list')) {
                $countries = DB::table('country_list')->orderBy('country_name')->get();
            } elseif (Schema::hasTable('countries')) {
                $countries = DB::table('countries')->orderBy('name')->get();
            }
        } catch (\Throwable $e) {
            $countries = collect();
        }

        // Merge modern `user_profiles` and `user_social_links` into the user object for the view
        try {
            if (Schema::hasTable('user_profiles')) {
                $profile = DB::table('user_profiles')->where('user_id', $user->id)->first();
                if ($profile) {
                    // map modern profile fields onto the legacy user properties/helpers used by the view
                    if (isset($profile->website)) $user->homepage = $profile->website;
                    if (isset($profile->about)) $user->about_me = $profile->about;
                    if (isset($profile->birthdate)) $user->birth = $profile->birthdate;
                    if (isset($profile->gender)) $user->gender = $profile->gender;
                    if (isset($profile->country_code)) $user->country_code = $profile->country_code;
                    if (isset($profile->avatar_hash)) $user->icon = $profile->avatar_hash;
                    if (isset($profile->cover_image)) $user->picture = $profile->cover_image;
                    if (isset($profile->signature)) $user->signature = $profile->signature;
                    if (isset($profile->description)) $user->description = $profile->description;
                }
            }
        } catch (\Throwable $e) {
            // ignore profile merge errors
        }

        try {
            if (Schema::hasTable('user_social_links')) {
                $social = DB::table('user_social_links')->where('user_id', $user->id)->first();
                if ($social) {
                    $user->social = $social;
                }
            }
        } catch (\Throwable $e) {
            // ignore social links errors
        }

        // Parse birth date parts after merging `user_profiles` so profile birthdate is used
        if (! empty($user->birth)) {
            try {
                $dt = Carbon::parse($user->birth);
                $birthDay = $dt->format('d');
                $birthMonth = $dt->format('m');
                $birthYear = $dt->format('Y');
            } catch (\Throwable $e) {
                // ignore parse errors
            }
        }

        return view('legacy::user', [
            'user' => $user,
            'birthDay' => $birthDay,
            'birthMonth' => $birthMonth,
            'birthYear' => $birthYear,
            'countries' => $countries,
        ]);
    }
}
