<?php

namespace App\Http\Controllers\Mobile;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Mail;
use App\Mail\OtpMail;

class UserController extends Controller
{
    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'ok' => false,
                'message' => 'Validasi gagal',
                'errors' => $validator->errors()
            ], 422);
        }

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

        if (!$user || !Hash::check($request->password, $user->password)) {
            return response()->json([
                'ok' => false,
                'message' => 'Email atau password salah'
            ], 401);
        }

        // Optional: buat token sanctum jika pakai
        $token = $user->createToken('mobile-token')->plainTextToken ?? null;

        return response()->json([
            'ok' => true,
            'message' => 'Login berhasil',
            'token' => $token,
            'data' => [
                'id' => $user->id,
                'nik' => $user->nik,
                'name' => $user->name,
                'tempat_lahir' => $user->tempat_lahir,
                'tanggal_lahir' => optional($user->tanggal_lahir)->toDateString(),
                'email' => $user->email,
                'role' => $user->role,
                'jabatan' => $user->jabatan,
                'phone' => $user->phone,
                'no_telepon' => $user->no_telepon,
                'employee_id' => $user->employee_id,
                'status' => $user->status,
                'address' => $user->address,
                'alamat' => $user->alamat,
                'hire_date' => optional($user->hire_date)->toDateString(),
                'jenis_kelamin' => $user->jenis_kelamin,
                'url_photo' => $user->url_photo,
            ]
        ]);
    }

    public function lupaKataSandi(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|string|email|max:255',
        ]);

        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()->first()], 422);
        }

        $type = $request->input('type');

        if ($type == 'email') {
            $user = User::where('email', $request->email)->first();
            if (!$user) {
                return response()->json([
                    'status' => false,
                    'message' => 'Email tidak terdaftar'
                ], 404);
            }

            // Generate OTP (6-digit random number)
            $otp = rand(10000, 99999);

            // Save OTP to the user record
            $user->otp = $otp;
            $user->otp_expires_at = now()->addMinutes(10); // OTP valid for 10 minutes
            $user->save();

            // Send OTP via email
            try {
                Mail::to($user->email)->send(new OtpMail($otp));
                \Log::info("OTP email sent to {$user->email}");
            } catch (\Exception $e) {
                \Log::error('Gagal mengirim email: ' . $e->getMessage());
                return response()->json(['error' => 'Gagal mengirim email OTP'], 500);
            }

            return response()->json([
                'status' => true,
                'message' => 'Kode OTP telah dikirim ke email Anda',
            ], 200);
        } elseif ($type == 'password') {
            $validator = Validator::make($request->all(), [
                'email' => 'required|string|email|max:255',
                'otp' => 'required|integer',
                'password' => 'required|string|min:8|confirmed',
            ]);

            if ($validator->fails()) {
                return response()->json(['error' => $validator->errors()->first()], 422);
            }

            $user = User::where('email', $request->email)->first();
            if (!$user) {
                return response()->json(['error' => 'Email tidak terdaftar'], 404);
            }

            // Verify OTP
            if ($user->otp !== (int) $request->otp || now()->greaterThan($user->otp_expires_at)) {
                return response()->json(['error' => 'Kode OTP tidak valid atau telah kedaluwarsa'], 400);
            }

            // Update password
            $user->password = bcrypt($request->password);
            $user->otp = null; // Clear OTP after successful password reset
            $user->otp_expires_at = null;
            $user->save();

            return response()->json([
                'status' => 'success',
                'message' => 'Password berhasil diperbarui',
            ], 200);
        } else {
            return response()->json(['error' => 'Tipe tidak valid'], 400);
        }
    }
    public function resetPassword(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email|exists:users,email',
            'password' => 'required|min:6|confirmed',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => false,
                'message' => $validator->errors()->first()
            ], 422);
        }

        try {
            $user = User::where('email', $request->email)->first();
            $user->password = Hash::make($request->password);
            $user->save();

            return response()->json([
                'status' => true,
                'message' => 'Password berhasil dibuat'
            ], 200);

        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => 'Gagal membuat password'
            ], 500);
        }
    }

    public function riwayatHariIni(Request $request)
    {
        $userId = $request->user_id;
        $date   = $request->date ?? now()->toDateString();
    
        $absen = Absensi::where('user_id', $userId)
            ->whereDate('tanggal', $date)
            ->first();
    
        return response()->json([
            'ok' => true,
            'data' => $absen ? [
                'check_in'  => $absen->check_in,
                'check_out' => $absen->check_out,
            ] : null
        ]);
    }
    public function getUser($id)
{
    $user = User::find($id);

    if (!$user) {
        return response()->json([
            'ok' => false,
            'message' => 'User tidak ditemukan'
        ]);
    }

    return response()->json([
        'ok' => true,
        'data' => [
            'id' => $user->id,
            'nama' => $user->nama,
            'foto' => $user->foto 
                ? url('storage/pegawai/' . $user->foto)
                : null,
        ]
    ]);
}
}

