<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\PelangganModel;

class PelangganController extends Controller
{
    public function index()
    {
        return view('layout.main', ['page' => 'pelanggan']);
    }

    public function data()
    {
        $pm = new PelangganModel();
        $data = $pm->getAll();
        return response()->json($data);
    }

    public function store(Request $request)
    {
        $request->validate([
            'nama_pelanggan' => 'required',
            'alamat' => 'required',
            'no_telp' => 'required',
            'jenis_kelamin' => 'required'
        ]);

        // ambil ID terakhir
        $lastId = DB::table('pelanggan')->max('id_pelanggan');
        $newId = $lastId ? $lastId + 1 : 1;

        DB::table('pelanggan')->insert([
            'id_pelanggan' => $newId,
            'nama_pelanggan' => $request->nama_pelanggan,
            'alamat' => $request->alamat,
            'no_telp' => $request->no_telp,
            'jenis_kelamin' => $request->jenis_kelamin
        ]);

        return redirect('/pelanggan')->with('success', 'Pelanggan berhasil ditambahkan');
    }

    public function edit($id)
    {
        $pelanggan = DB::table('pelanggan')
            ->where('id_pelanggan', $id)
            ->first();

        return view('layout.main', [
            'page' => 'pelanggan_edit',
            'pelanggan' => $pelanggan
        ]);
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'nama_pelanggan' => 'required',
            'alamat' => 'required',
            'no_telp' => 'required',
            'jenis_kelamin' => 'required'
        ]);

        DB::table('pelanggan')
            ->where('id_pelanggan', $id)
            ->update([
                'nama_pelanggan' => $request->nama_pelanggan,
                'alamat' => $request->alamat,
                'no_telp' => $request->no_telp,
                'jenis_kelamin' => $request->jenis_kelamin
            ]);

        return redirect('/pelanggan')->with('success', 'Data berhasil diperbarui');
    }

    public function delete($id)
    {
        DB::table('pelanggan')
            ->where('id_pelanggan', $id)
            ->delete();

        return response()->json(['success' => true]);
    }

}
