<?php

namespace App\Http\Controllers;

use App\Models\Teknisi;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;

class TeknisiController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = Teknisi::query();
        
        // Handle search
        if ($request->has('q') && $request->q != '') {
            $searchTerm = $request->q;
            $query->where(function($q) use ($searchTerm) {
                $q->where('nama', 'LIKE', "%{$searchTerm}%")
                  ->orWhere('email', 'LIKE', "%{$searchTerm}%")
                  ->orWhere('no_telephone', 'LIKE', "%{$searchTerm}%");
            });
        }
        
        $teknisis = $query->latest()->get();
        
        // Jika request dari AJAX, return JSON
        if ($request->ajax() || $request->wantsJson()) {
            return response()->json([
                'success' => true,
                'data' => $teknisis
            ]);
        }
        
        // Jika request biasa, return view
        return view('Admin.KelolaTeknisi.Teknisi', compact('teknisis'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('teknisi.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'nama' => 'required|string|max:100',
            'tanggal_lahir' => 'required|date',
            'alamat' => 'required|string',
            'email' => 'nullable|email|max:100|unique:teknisis,email',
            'no_telephone' => 'required|string|max:15',
            'tanggal_masuk' => 'required|date',
            'status' => 'required|in:aktif,tidak_aktif',
        ], [
            'nama.required' => 'Nama wajib diisi',
            'nama.max' => 'Nama maksimal 100 karakter',
            'tanggal_lahir.required' => 'Tanggal lahir wajib diisi',
            'tanggal_lahir.date' => 'Format tanggal lahir tidak valid',
            'alamat.required' => 'Alamat wajib diisi',
            'email.email' => 'Format email tidak valid',
            'email.unique' => 'Email sudah terdaftar',
            'no_telephone.required' => 'Nomor telephone wajib diisi',
            'no_telephone.max' => 'Nomor telephone maksimal 15 karakter',
            'tanggal_masuk.required' => 'Tanggal masuk wajib diisi',
            'tanggal_masuk.date' => 'Format tanggal masuk tidak valid',
            'status.required' => 'Status wajib dipilih',
            'status.in' => 'Status harus aktif atau tidak_aktif',
        ]);

        if ($validator->fails()) {
            // Jika AJAX request
            if (request()->ajax() || request()->wantsJson()) {
                return response()->json([
                    'success' => false,
                    'errors' => $validator->errors()
                ], 422);
            }
            
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        try {
            $teknisi = Teknisi::create($request->all());

            // Jika AJAX request
            if (request()->ajax() || request()->wantsJson()) {
                return response()->json([
                    'success' => true,
                    'message' => 'Data teknisi berhasil ditambahkan',
                    'data' => $teknisi
                ], 201);
            }

            return redirect()->route('teknisi.index')
                ->with('success', 'Data teknisi berhasil ditambahkan');
        } catch (\Exception $e) {
            Log::error('Error creating teknisi: ' . $e->getMessage());
            
            // Jika AJAX request
            if (request()->ajax() || request()->wantsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Gagal menambahkan data teknisi: ' . $e->getMessage()
                ], 500);
            }
            
            return redirect()->back()
                ->with('error', 'Gagal menambahkan data teknisi: ' . $e->getMessage())
                ->withInput();
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        try {
            $teknisi = Teknisi::where('id_teknisi', $id)->firstOrFail();
            
            // Jika AJAX request, return JSON
            if (request()->ajax() || request()->wantsJson()) {
                return response()->json([
                    'success' => true,
                    'data' => $teknisi
                ]);
            }
            
            return view('teknisi.show', compact('teknisi'));
        } catch (\Exception $e) {
            if (request()->ajax() || request()->wantsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Data teknisi tidak ditemukan'
                ], 404);
            }
            
            return redirect()->route('teknisi.index')
                ->with('error', 'Data teknisi tidak ditemukan');
        }
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        try {
            $teknisi = Teknisi::where('id_teknisi', $id)->firstOrFail();
            return view('teknisi.edit', compact('teknisi'));
        } catch (\Exception $e) {
            return redirect()->route('teknisi.index')
                ->with('error', 'Data teknisi tidak ditemukan');
        }
    }

    /**
     * Update the specified resource in storage.
     */
    
    public function update(Request $request, string $id)
{
    try {
        $teknisi = Teknisi::where('id_teknisi', $id)->firstOrFail();

        // Log untuk debugging
        Log::info('Update Teknisi Request', [
            'id' => $id,
            'request_data' => $request->all()
        ]);

        // Validasi - TANPA tanggal_lahir dan tanggal_masuk karena tidak boleh diubah
        $validator = Validator::make($request->all(), [
            'nama' => 'required|string|max:100',
            'alamat' => 'required|string',
            'email' => 'nullable|email|max:100|unique:teknisis,email,' . $id . ',id_teknisi', 
            'no_telephone' => 'required|string|max:15',
            'status' => 'required|in:aktif,tidak_aktif',
            'tanggal_masuk' => 'required|date',
        ], [
            'nama.required' => 'Nama wajib diisi',
            'nama.max' => 'Nama maksimal 100 karakter',
            'alamat.required' => 'Alamat wajib diisi',
            'email.email' => 'Format email tidak valid',
            'email.unique' => 'Email sudah terdaftar',
            'no_telephone.required' => 'Nomor telephone wajib diisi',
            'no_telephone.max' => 'Nomor telephone maksimal 15 karakter',
            'status.required' => 'Status wajib dipilih',
            'status.in' => 'Status harus aktif atau tidak_aktif',
            'tanggal_masuk.required' => 'Tanggal masuk wajib diisi',
            'tanggal_masuk.date' => 'Format tanggal masuk tidak valid',
        ]);

        // Allow deactivation even if unpaid kasbon; a warning will be shown in the UI.
        // The check is now performed in the view for visual indication.


        if ($validator->fails()) {
            Log::warning('Validation Failed', [
                'errors' => $validator->errors()->toArray()
            ]);
            
            // Jika AJAX request
            if (request()->ajax() || request()->wantsJson()) {
                return response()->json([
                    'success' => false,
                    'errors' => $validator->errors()
                ], 422);
            }
            
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        // Update data
        $teknisi->update([
            'nama' => $request->nama,
            'alamat' => $request->alamat,
            'email' => $request->email,
            'no_telephone' => $request->no_telephone,
            'status' => $request->status,
            'tanggal_masuk' => $request->tanggal_masuk,
        ]);

        Log::info('Teknisi Updated Successfully', [
            'id' => $id,
            'updated_data' => $teknisi->fresh()->toArray()
        ]);

        // Jika AJAX request
        if (request()->ajax() || request()->wantsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Data teknisi berhasil diperbarui',
                'data' => $teknisi
            ]);
        }

        return redirect()->route('teknisi.index')
            ->with('success', 'Data teknisi berhasil diperbarui');
            
    } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
        Log::error('Teknisi Not Found', ['id' => $id]);
        
        // Jika AJAX request
        if (request()->ajax() || request()->wantsJson()) {
            return response()->json([
                'success' => false,
                'message' => 'Data teknisi tidak ditemukan'
            ], 404);
        }
        
        return redirect()->route('teknisi.index')
            ->with('error', 'Data teknisi tidak ditemukan');
            
    } catch (\Exception $e) {
        Log::error('Update Teknisi Failed', [
            'id' => $id,
            'error' => $e->getMessage(),
            'trace' => $e->getTraceAsString()
        ]);
        
        // Jika AJAX request
        if (request()->ajax() || request()->wantsJson()) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal memperbarui data teknisi: ' . $e->getMessage()
            ], 500);
        }
        
        return redirect()->back()
            ->with('error', 'Gagal memperbarui data teknisi: ' . $e->getMessage())
            ->withInput();
    }
}
    /**
     * Search teknisi
     */
    public function search(Request $request)
    {
        $query = $request->get('q');
        
        $teknisis = Teknisi::where('nama', 'LIKE', "%{$query}%")
            ->orWhere('email', 'LIKE', "%{$query}%")
            ->orWhere('no_telephone', 'LIKE', "%{$query}%")
            ->latest()
            ->get();
        
        // Jika AJAX request
        if (request()->ajax() || request()->wantsJson()) {
            return response()->json([
                'success' => true,
                'data' => $teknisis
            ]);
        }
        
        return view('Admin.KelolaTeknisi.Teknisi', compact('teknisis'));
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        try {
            $teknisi = Teknisi::where('id_teknisi', $id)->firstOrFail();

            // Cek tunggakan kasbon
            $unpaidKasbon = \App\Models\Kasbon::where('id_teknisi', $id)
                ->where('status', 'belum_lunas')
                ->sum('jumlah_kasbon');

            if ($unpaidKasbon > 0) {
                return response()->json([
                    'success' => false,
                    'message' => 'Teknisi tidak dapat dihapus karena masih memiliki tunggakan kasbon sebesar Rp ' . number_format($unpaidKasbon, 0, ',', '.') . '.'
                ], 422);
            }

            $teknisi->delete();

            return response()->json([
                'success' => true,
                'message' => 'Data teknisi berhasil dihapus'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal menghapus data teknisi: ' . $e->getMessage()
            ], 500);
        }
    }
}