<?php

namespace App\Http\Controllers\Siswa;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Carbon\Carbon;

class ParentConnectionController extends Controller
{
    /**
     * Menampilkan halaman koneksi orang tua
     */
    public function index()
    {
        $user = Auth::user();
        
        // Cek apakah sudah terhubung dengan orang tua
        $connection = null;
        if ($user->parent_id) {
            // Ambil data orang tua
            $parent = User::find($user->parent_id);
            if ($parent) {
                $connection = $parent;
            }
        }
        
        // Cek apakah ada kode pending
        $pendingConnection = null;
        if ($user->parent_code) {
            $pendingConnection = (object)[
                'connection_code' => $user->parent_code
            ];
        }
        
        return view('siswa.parent-connection', compact('connection', 'pendingConnection'));
    }

    /**
     * Generate kode koneksi baru
     */
    public function generateCode(Request $request)
    {
        $user = Auth::user();
        
        // Generate kode 8 digit (huruf dan angka) - PASTIKAN UNIK
        do {
            $code = strtoupper(substr(md5(uniqid() . $user->id . time()), 0, 8));
            // Cek apakah kode sudah ada
            $existing = User::where('parent_code', $code)->first();
        } while ($existing);
        
        // Simpan kode ke database
        $user->parent_code = $code;
        $user->save();
        
        return redirect()->route('siswa.parent-connection')
            ->with('success', 'Kode koneksi berhasil digenerate. Berikan kode ini kepada orang tua Anda.');
    }

    /**
     * Hapus kode koneksi (jika ingin membatalkan)
     */
    public function clearCode(Request $request)
    {
        $user = Auth::user();
        
        $user->parent_code = null;
        $user->save();
        
        return redirect()->route('siswa.parent-connection')
            ->with('success', 'Kode koneksi berhasil dihapus.');
    }
}