<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\WebUser;
use App\Models\Member;
use App\Models\Simpanan;
use App\Models\Pinjaman;
use App\Models\Angsuran;
use App\Models\Pengajuan;
use App\Models\JenisSimpanan;
use App\Models\JenisPinjaman;
use App\Models\ActivityLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

class MobileApiController extends Controller
{
    /**
     * Login
     */
    public function login(Request $request)
    {
        $request->validate([
            'nik' => 'required', // bisa nik atau no_telp
            'password' => 'required'
        ]);

        // Cari member berdasarkan NIK atau no_telp
        $member = Member::where('nik', $request->nik)
            ->orWhere('no_telp', $request->nik)
            ->first();

        if (!$member) {
            throw ValidationException::withMessages([
                'nik' => ['NIK atau nomor telepon tidak ditemukan.'],
            ]);
        }

        // Cek password langsung dari tabel member
        if (!Hash::check($request->password, $member->password)) {
            throw ValidationException::withMessages([
                'nik' => ['Password salah.'],
            ]);
        }

        if ($member->status !== 'aktif') {
            throw ValidationException::withMessages([
                'nik' => ['Akun Anda tidak aktif.'],
            ]);
        }

        // Create token menggunakan Sanctum dari Member model
        $token = $member->createToken('mobile-app')->plainTextToken;

        // Log activity
        ActivityLog::logActivity('login', $member->id, $member->nama, 'Login', 'User berhasil login', $request->ip(), $request->userAgent());

        return response()->json([
            'success' => true,
            'message' => 'Login berhasil',
            'data' => [
                'member' => $member,
                'token' => $token
            ]
        ]);
    }

    /**
     * Logout
     */
    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();

        ActivityLog::logActivity('logout', $request->user()->id, $request->user()->nama, 'Logout', 'User logout', $request->ip(), $request->userAgent());

        return response()->json([
            'success' => true,
            'message' => 'Logout berhasil'
        ]);
    }

    /**
     * Register new user
     */
    public function register(Request $request)
    {
        $request->validate([
            'nik' => 'required|unique:member,nik',
            'nama' => 'required|string|max:200',
            'password' => 'required|min:6|confirmed',
            'no_telp' => 'required|string|max:50',
            'email' => 'nullable|email',
        ]);

        $member = Member::create([
            'nik' => $request->nik,
            'nama' => $request->nama,
            'password' => Hash::make($request->password),
            'no_telp' => $request->no_telp,
            'email' => $request->email,
            'status' => 'aktif',
            'unit_kerja' => $request->unit_kerja ?? '',
        ]);

        $token = $member->createToken('mobile-app')->plainTextToken;

        return response()->json([
            'success' => true,
            'message' => 'Registrasi berhasil',
            'data' => [
                'member' => $member,
                'token' => $token
            ]
        ], 201);
    }

    /**
     * Get user profile
     */
    public function profile(Request $request)
    {
        return response()->json([
            'success' => true,
            'data' => $request->user()
        ]);
    }

    /**
     * Update profile
     */
    public function updateProfile(Request $request)
    {
        $member = $request->user();

        $request->validate([
            'email' => 'nullable|email',
            'no_telp' => 'nullable|string|max:50',
            'alamat' => 'nullable|string|max:500'
        ]);

        $member->update($request->only(['email', 'no_telp', 'alamat']));

        return response()->json([
            'success' => true,
            'message' => 'Profile berhasil diupdate',
            'data' => $member
        ]);
    }

    /**
     * Change password
     */
    public function changePassword(Request $request)
    {
        $request->validate([
            'old_password' => 'required',
            'new_password' => 'required|min:6|confirmed'
        ]);

        $member = $request->user();

        if (!Hash::check($request->old_password, $member->password)) {
            throw ValidationException::withMessages([
                'old_password' => ['Password lama salah.'],
            ]);
        }

        $member->update([
            'password' => Hash::make($request->new_password)
        ]);

        ActivityLog::logActivity('security', $member->id, $member->nama, 'Change Password', 'User mengganti password', $request->ip(), $request->userAgent());

        return response()->json([
            'success' => true,
            'message' => 'Password berhasil diubah'
        ]);
    }

    /**
     * Upload profile photo
     */
    public function uploadPhoto(Request $request)
    {
        $request->validate([
            'photo' => 'required|image|mimes:jpeg,png,jpg|max:2048'
        ]);

        $member = $request->user();

        if ($request->hasFile('photo')) {
            $file = $request->file('photo');
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('uploads/profiles'), $filename);

            // Note: foto_profil field tidak ada di tabel member yang baru
            // Bisa ditambahkan ke tabel atau disimpan di tempat lain
        }

        return response()->json([
            'success' => true,
            'message' => 'Foto profil berhasil diupload',
            'data' => $member
        ]);
    }

    /**
     * Get access logs
     */
    public function getAccessLogs(Request $request)
    {
        $logs = ActivityLog::where('user_id', $request->user()->id)
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        return response()->json([
            'success' => true,
            'data' => $logs
        ]);
    }

    /**
     * Dashboard data
     */
    public function getDashboard(Request $request)
    {
        $member = $request->user();

        // Total simpanan dari field-field total di tabel member
        $totalSimpanan = $member->total_pokok + $member->total_wajib + $member->total_tabungan +
            $member->total_mudarabah + $member->total_property;

        $totalPinjaman = Pinjaman::where('id_member', $member->id)
            ->where('is_lunas', 0)
            ->sum('jumlah_pinjaman');

        $recentSimpanan = Simpanan::where('id_member', $member->id)
            ->with('jenisSimpanan')
            ->orderBy('tanggal', 'desc')
            ->limit(5)
            ->get();

        $recentPinjaman = Pinjaman::where('id_member', $member->id)
            ->with('jenisPinjaman')
            ->orderBy('tanggal', 'desc')
            ->limit(5)
            ->get();

        return response()->json([
            'success' => true,
            'data' => [
                'member' => $member,
                'summary' => [
                    'total_simpanan' => $totalSimpanan,
                    'total_pinjaman' => $totalPinjaman,
                    'total_pokok' => $member->total_pokok,
                    'total_wajib' => $member->total_wajib,
                    'total_tabungan' => $member->total_tabungan,
                ],
                'recent_simpanan' => $recentSimpanan,
                'recent_pinjaman' => $recentPinjaman
            ]
        ]);
    }

    /**
     * Get Simpanan List
     */
    public function getSimpanan(Request $request)
    {
        $member = $request->user();

        $simpanan = Simpanan::where('id_member', $member->id)
            ->with('jenisSimpanan')
            ->orderBy('tanggal', 'desc')
            ->paginate(15);

        return response()->json([
            'success' => true,
            'data' => $simpanan
        ]);
    }

    /**
     * Get Simpanan Detail
     */
    public function getSimpananDetail($id, Request $request)
    {
        $member = $request->user();

        $simpanan = Simpanan::where('id', $id)
            ->where('id_member', $member->id)
            ->with('jenisSimpanan')
            ->firstOrFail();

        return response()->json([
            'success' => true,
            'data' => $simpanan
        ]);
    }

    /**
     * Get Simpanan History
     */
    public function getSimpananHistory(Request $request)
    {
        $member = $request->user();

        $history = Simpanan::where('id_member', $member->id)
            ->with('jenisSimpanan')
            ->whereBetween('tanggal', [
                $request->start_date ?? now()->subYear(),
                $request->end_date ?? now()
            ])
            ->orderBy('tanggal', 'desc')
            ->get();

        return response()->json([
            'success' => true,
            'data' => $history
        ]);
    }

    /**
     * Get Simpanan Summary
     */
    public function getSimpananSummary(Request $request)
    {
        $member = $request->user();

        $summary = [
            'total_pokok' => $member->total_pokok,
            'total_wajib' => $member->total_wajib,
            'total_tabungan' => $member->total_tabungan,
            'total_mudarabah' => $member->total_mudarabah,
            'total_property' => $member->total_property,
            'total_qurban' => $member->total_qurban,
            'total_umrah' => $member->total_umrah,
            'total_haji' => $member->total_haji,
            'total_ijah' => $member->total_ijah,
            'total_simpanan' => $member->total_pokok + $member->total_wajib + $member->total_tabungan +
                $member->total_mudarabah + $member->total_property,
        ];

        return response()->json([
            'success' => true,
            'data' => $summary
        ]);
    }

    /**
     * Get Pinjaman List
     */
    public function getPinjaman(Request $request)
    {
        $member = $request->user();

        $pinjaman = Pinjaman::where('id_member', $member->id)
            ->with('jenisPinjaman')
            ->orderBy('tanggal', 'desc')
            ->paginate(15);

        return response()->json([
            'success' => true,
            'data' => $pinjaman
        ]);
    }

    /**
     * Get Pinjaman Detail
     */
    public function getPinjamanDetail($id, Request $request)
    {
        $member = $request->user();

        $pinjaman = Pinjaman::where('id', $id)
            ->where('id_member', $member->id)
            ->with(['jenisPinjaman', 'angsuran'])
            ->firstOrFail();

        return response()->json([
            'success' => true,
            'data' => $pinjaman
        ]);
    }

    /**
     * Get Pinjaman History
     */
    public function getPinjamanHistory(Request $request)
    {
        $member = $request->user();

        $history = Pinjaman::where('id_member', $member->id)
            ->with('jenisPinjaman')
            ->whereBetween('tanggal', [
                $request->start_date ?? now()->subYear(),
                $request->end_date ?? now()
            ])
            ->orderBy('tanggal', 'desc')
            ->get();

        return response()->json([
            'success' => true,
            'data' => $history
        ]);
    }

    /**
     * Get Angsuran
     */
    public function getAngsuran($pinjamanId, Request $request)
    {
        $member = $request->user();

        $pinjaman = Pinjaman::where('id', $pinjamanId)
            ->where('id_member', $member->id)
            ->firstOrFail();

        $angsuran = Angsuran::where('id_pinjaman', $pinjaman->id)
            ->orderBy('bayar_ke')
            ->get();

        return response()->json([
            'success' => true,
            'data' => $angsuran
        ]);
    }

    /**
     * Simulasi Pinjaman
     */
    public function simulasiPinjaman(Request $request)
    {
        $request->validate([
            'jumlah_pinjaman' => 'required|numeric|min:100000',
            'tenor' => 'required|integer|min:1|max:60',
            'id_jenis_pinjaman' => 'required|exists:jenis_pinjaman,id'
        ]);

        $jenisPinjaman = JenisPinjaman::findOrFail($request->id_jenis_pinjaman);
        $jumlahPinjaman = $request->jumlah_pinjaman;
        $tenor = $request->tenor;

        // Asumsi bunga flat (bisa disesuaikan dengan jenis bunga di database)
        $bungaPersen = 1.5; // 1.5% per bulan (contoh)
        $totalBunga = ($jumlahPinjaman * $bungaPersen / 100) * $tenor;
        $totalBayar = $jumlahPinjaman + $totalBunga;
        $angsuranPerBulan = $totalBayar / $tenor;

        return response()->json([
            'success' => true,
            'data' => [
                'jenis_pinjaman' => $jenisPinjaman->nama_pinjaman,
                'jumlah_pinjaman' => $jumlahPinjaman,
                'tenor' => $tenor,
                'bunga_persen' => $bungaPersen,
                'total_bunga' => round($totalBunga, 0),
                'total_bayar' => round($totalBayar, 0),
                'angsuran_per_bulan' => round($angsuranPerBulan, 0)
            ]
        ]);
    }

    /**
     * Pengajuan Pinjaman
     */
    public function pengajuanPinjaman(Request $request)
    {
        $request->validate([
            'id_jenis_pinjaman' => 'required|exists:jenis_pinjaman,id',
            'jumlah' => 'required|numeric|min:100000',
            'tenor' => 'required|integer|min:1|max:60',
            'foto' => 'nullable|string',
        ]);

        $member = $request->user();

        $pengajuan = Pengajuan::create([
            'nik' => $member->nik,
            'nama' => $member->nama,
            'jenis' => 'pinjaman',
            'id_jenis_pinjaman' => $request->id_jenis_pinjaman,
            'jumlah' => $request->jumlah,
            'tenor' => $request->tenor,
            'foto' => $request->foto,
            'tanggal' => now(),
            'is_proses' => 0
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Pengajuan pinjaman berhasil disubmit',
            'data' => $pengajuan
        ], 201);
    }

    /**
     * Get Pengajuan List
     */
    public function getPengajuan(Request $request)
    {
        $member = $request->user();

        $pengajuan = Pengajuan::where('nik', $member->nik)
            ->with(['jenisPinjaman', 'jenisSimpanan'])
            ->orderBy('tanggal', 'desc')
            ->paginate(15);

        return response()->json([
            'success' => true,
            'data' => $pengajuan
        ]);
    }

    /**
     * Get Pengajuan Detail
     */
    public function getPengajuanDetail($id, Request $request)
    {
        $member = $request->user();

        $pengajuan = Pengajuan::where('id', $id)
            ->where('nik', $member->nik)
            ->with(['jenisPinjaman', 'jenisSimpanan'])
            ->firstOrFail();

        return response()->json([
            'success' => true,
            'data' => $pengajuan
        ]);
    }

    /**
     * Get Jenis Simpanan
     */
    public function getJenisSimpanan()
    {
        $jenis = JenisSimpanan::all();

        return response()->json([
            'success' => true,
            'data' => $jenis
        ]);
    }

    /**
     * Get Jenis Pinjaman
     */
    public function getJenisPinjaman()
    {
        $jenis = JenisPinjaman::all();

        return response()->json([
            'success' => true,
            'data' => $jenis
        ]);
    }

    /**
     * Forgot Password - Send OTP
     */
    public function forgotPassword(Request $request)
    {
        $request->validate([
            'nik' => 'required|exists:members,nik'
        ]);

        $member = Member::where('nik', $request->nik)->first();

        if (!$member->email) {
            return response()->json([
                'success' => false,
                'message' => 'Email tidak terdaftar untuk NIK ini'
            ], 422);
        }

        // Generate OTP (dalam produksi, kirim via email/SMS)
        $otp = rand(100000, 999999);

        // Simpan OTP ke cache/session (untuk demo, return langsung)
        // Cache::put("otp_{$request->nik}", $otp, now()->addMinutes(5));

        return response()->json([
            'success' => true,
            'message' => 'OTP telah dikirim ke email Anda',
            'otp' => $otp // Untuk testing only, hapus di production!
        ]);
    }

    /**
     * Verify OTP
     */
    public function verifyOtp(Request $request)
    {
        $request->validate([
            'nik' => 'required|exists:members,nik',
            'otp' => 'required|digits:6'
        ]);

        // Verifikasi OTP dari cache/session
        // $cachedOtp = Cache::get("otp_{$request->nik}");
        // if ($cachedOtp != $request->otp) {
        //     return response()->json(['success' => false, 'message' => 'OTP salah'], 422);
        // }

        return response()->json([
            'success' => true,
            'message' => 'OTP berhasil diverifikasi'
        ]);
    }

    /**
     * Reset Password
     */
    public function resetPassword(Request $request)
    {
        $request->validate([
            'nik' => 'required|exists:member,nik',
            'new_password' => 'required|min:6|confirmed'
        ]);

        $member = Member::where('nik', $request->nik)->first();

        if (!$member) {
            return response()->json([
                'success' => false,
                'message' => 'Member tidak ditemukan'
            ], 404);
        }

        $member->update([
            'password' => Hash::make($request->new_password)
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Password berhasil direset'
        ]);
    }
}
