<?php

namespace App\Http\Controllers;

use App\Models\Umkm;
use App\Models\Transaction;
use App\Models\BudgetPlan;
use App\Models\Contact;
use App\Services\AccountService;
use App\Mail\ContactMail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;

class UmkmController extends Controller
{
    // --- FITUR UMKM ---
    public function index() { return view('umkm.index', ['umkms' => Umkm::latest()->get()]); }
    
    public function indexApi() {
        return response()->json(['success' => true, 'data' => Umkm::latest()->get()], 200);
    }

    public function storeApi(Request $request) {
        $validator = Validator::make($request->all(), [
            'nama_usaha' => 'required|string|max:255',
            'jenis_usaha' => 'required|string|max:255',
            'no_telepon' => 'required|string|max:20',
            'nama_pemilik' => 'required|string|max:255',
            'alamat' => 'required|string',
            'modal_awal' => 'nullable|numeric',
        ]);

        if ($validator->fails()) return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
        
        $data = $validator->validated();
        $data['user_id'] = $request->user()->id;
        
        return response()->json(['success' => true, 'data' => Umkm::create($data)], 201);
    }

   // --- CRUD WEB (Internal Admin Panel) ---
public function create() {
    return view('umkm.create');
}

public function store(Request $request) {
    $validated = $request->validate([
        'nama_usaha'  => 'required|string|max:255',
        'nama_pemilik'=> 'required|string|max:255',
        'jenis_usaha' => 'required|string|max:255',
        'no_telepon'  => 'required|string|max:20',
        'alamat'      => 'required|string',
        'modal_awal'  => 'required|numeric',
        'email'       => 'required|email|max:255',
    ]);

    // Buat akun CASHEV (password acak) + kirim email berisi link & password
    $result = app(AccountService::class)->provision([
        'email' => $validated['email'],
        'name'  => $validated['nama_pemilik'],
    ], false);

    $umkmData = $validated;
    unset($umkmData['email']);
    $umkmData['user_id'] = $result['user']->id;

    $umkm = Umkm::create($umkmData);

    if ($result['is_new']) {
        $message = "Data UMKM {$umkm->nama_usaha} berhasil ditambahkan. Akun CASHEV dibuat & email berisi link + password telah dikirim ke {$validated['email']}.";
    } else {
        $message = "Data UMKM {$umkm->nama_usaha} berhasil ditambahkan. Email {$validated['email']} sudah terdaftar — gunakan akun yang sudah ada.";
    }

    return redirect()->route('umkm.index')->with('success', $message);
}

public function edit(Umkm $umkm) {
    return view('umkm.edit', compact('umkm'));
}

public function update(Request $request, Umkm $umkm) {
    $validated = $request->validate([
        'nama_usaha'  => 'required|string|max:255',
        'nama_pemilik'=> 'required|string|max:255',
        'jenis_usaha' => 'required|string|max:255',
        'no_telepon'  => 'required|string|max:20',
        'alamat'      => 'required|string',
        'modal_awal'  => 'nullable|numeric',
    ]);

    $umkm->update($validated);

    return redirect()->route('umkm.index')->with('success', 'Data UMKM berhasil diperbarui.');
}

public function destroy(Umkm $umkm) {
    $umkm->delete();

    return redirect()->route('umkm.index')->with('success', 'Data UMKM berhasil dihapus.');
}
    // --- FITUR FOTO PROFIL ---
    public function updatePhoto(Request $request) {
        $request->validate([
            'photo' => 'required|image|mimes:jpeg,png,jpg|max:2048',
        ]);

        $user = $request->user();

        if ($user->photo_url) {
            Storage::disk('public')->delete($user->photo_url);
        }

        $path = $request->file('photo')->store('profiles', 'public');
        $user->update(['photo_url' => $path]);

        return response()->json([
            'success' => true, 
            'message' => 'Foto profil berhasil diperbarui',
            'url' => asset('storage/' . $path)
        ]);
    }

    // --- FITUR TRANSAKSI ---
    public function getTransactions(Request $request) {
        return response()->json(Transaction::where('user_id', $request->user()->id)->latest()->get());
    }

    public function storeTransaction(Request $request) {
        $validated = $request->validate([
            'deskripsi' => 'required|string',
            'jumlah'    => 'required|numeric',
            'tipe'      => 'required|in:masuk,keluar',
            'tanggal'   => 'required|date',
            'mata_uang' => 'required|in:IDR,USD',
        ]);
        
        $validated['user_id'] = $request->user()->id;
        
        return response()->json(['success' => true, 'data' => Transaction::create($validated)], 201);
    }

    public function deleteTransaction(Request $request, $id) {
        $transaction = Transaction::where('user_id', $request->user()->id)->where('id', $id)->first();

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

        $transaction->delete();

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

    // --- FITUR BUDGET PLAN (DIPERBARUI) ---
    public function getBudgetPlan(Request $request) {
        $budget = BudgetPlan::where('user_id', $request->user()->id)->first();
        
        // Mengembalikan format camelCase yang sesuai dengan state React Anda
        return response()->json([
            'planModal'  => $budget ? (float)$budget->plan_modal : 0, 
            'planOmset'  => $budget ? (float)$budget->plan_omset : 0, 
            'planProfit' => $budget ? (float)$budget->plan_profit : 0
        ]);
    }

    public function updateBudgetPlan(Request $request) {
        $validated = $request->validate([
            'planModal'  => 'required|numeric',
            'planOmset'  => 'required|numeric',
            'planProfit' => 'required|numeric',
        ]);
        
        $budget = BudgetPlan::updateOrCreate(
            ['user_id' => $request->user()->id], 
            [
                'plan_modal'  => $validated['planModal'],
                'plan_omset'  => $validated['planOmset'],
                'plan_profit' => $validated['planProfit'],
            ]
        );
        
        // Mengembalikan respons dengan format yang sama agar Frontend bisa langsung memperbarui state
        return response()->json([
            'success' => true, 
            'planModal'  => (float)$budget->plan_modal,
            'planOmset'  => (float)$budget->plan_omset,
            'planProfit' => (float)$budget->plan_profit
        ]);
    }

    // --- FITUR HUBUNGI SUPPORT ---
    public function sendContact(Request $request) {
        $validated = $request->validate([
            'nama'     => 'required|string|max:255',
            'whatsapp' => 'required|string|max:20',
            'usaha'    => 'nullable|string|max:255',
            'pesan'    => 'required|string|max:2000',
        ]);

        // Simpan pesan ke database agar tampil di halaman admin (support)
        Contact::create([
            'user_id'  => $request->user()->id,
            'nama'     => $validated['nama'],
            'whatsapp' => $validated['whatsapp'],
            'usaha'    => $validated['usaha'] ?? null,
            'pesan'    => $validated['pesan'],
            'status'   => 'open',
        ]);

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