<?php
if (!isset($conn)) {
    $conn = mysqli_connect("localhost", "root", "", "db_rpl2526");
}

if (!$conn) {
    die("Koneksi database gagal: " . mysqli_connect_error());
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $nama_admin    = mysqli_real_escape_string($conn, $_POST['nama_admin'] ?? '');
    $alamat_admin  = mysqli_real_escape_string($conn, $_POST['alamat_admin'] ?? '');
    $telepon_admin = mysqli_real_escape_string($conn, $_POST['telepon_admin'] ?? '');
    $jenis_kelamin = mysqli_real_escape_string($conn, $_POST['jenis_kelamin'] ?? '');
    $email         = mysqli_real_escape_string($conn, $_POST['email'] ?? '');
    $password      = $_POST['password'] ?? '';
    $password2     = $_POST['password2'] ?? '';

    if ($nama_admin == '' || $alamat_admin == '' || $telepon_admin == '' || $email == '') {
        echo "<script>alert('Semua field teks wajib diisi!'); history.back();</script>";
        exit;
    }
    if ($password == '' || $password != $password2) {
        echo "<script>alert('Password tidak sesuai atau kosong!'); history.back();</script>";
        exit;
    }

    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    // =========================================================
    // 1. GENERATE ID USER FORMAT SAMA (ADM0000001)
    // =========================================================
    $q_max = mysqli_query($conn, "SELECT id_user FROM tbl_users WHERE id_user LIKE 'ADM%' ORDER BY LENGTH(id_user) DESC, id_user DESC LIMIT 1");
    $r_max = mysqli_fetch_assoc($q_max);

    if ($r_max && !empty($r_max['id_user'])) {
        // Ambil angkanya saja dari "ADM0000002" -> 2
        $number = (int) preg_replace('/[^0-9]/', '', $r_max['id_user']);
        $next_number = $number + 1;
    } else {
        $next_number = 1;
    }

    // Format ulang menjadi ADM + 6 digit angka (contoh: ADM0000003)
    $next_id_user = "ADM" . sprintf("%06d", $next_number);

    // Insert ke tbl_users
    $query_user = "INSERT INTO tbl_users (id_user, email, password, role) VALUES ('$next_id_user', '$email', '$hashed_password', 1)";
    
    try {
        $exec_user = mysqli_query($conn, $query_user);
    } catch (Exception $e) {
        $exec_user = false;
        $error_msg = $e->getMessage();
    }

    if ($exec_user) {
        $id_user = $next_id_user;

        // =========================
        // 2. UPLOAD FOTO ADMIN
        // =========================
        $nama_foto_db = '';

        if (isset($_FILES['photo_admin']) && $_FILES['photo_admin']['error'] == UPLOAD_ERR_OK) {
            $nama_file = $_FILES['photo_admin']['name'];
            $tmp_file  = $_FILES['photo_admin']['tmp_name'];
            $ekstensi  = strtolower(pathinfo($nama_file, PATHINFO_EXTENSION));
            $allowed   = ['jpg', 'jpeg', 'png', 'bmp'];

            if (in_array($ekstensi, $allowed)) {
                // Folder upload relatif dari file ini
                $target_dir = "../uploads/admin/";
                if (!is_dir($target_dir)) {
                    mkdir($target_dir, 0777, true);
                }

                $nama_foto_baru = uniqid("admin_") . "." . $ekstensi;
                $target_file = $target_dir . $nama_foto_baru;

                if (move_uploaded_file($tmp_file, $target_file)) {
                    // Simpan nama file atau path relatif ke database
                    $nama_foto_db = $nama_foto_baru; 
                }
            }
        }

        // =========================
        // 3. INSERT KE tbl_admin
        // =========================
        $query_admin = "INSERT INTO tbl_admin 
            (id_user, nama_admin, telepon_admin, alamat_admin, jenis_kelamin, path_photo_admin) 
            VALUES 
            ('$id_user', '$nama_admin', '$telepon_admin', '$alamat_admin', '$jenis_kelamin', '$nama_foto_db')";

        try {
            $exec_admin = mysqli_query($conn, $query_admin);
        } catch (Exception $e) {
            $exec_admin = false;
            $error_admin_msg = $e->getMessage();
        }

        if ($exec_admin) {
            echo "
            <script>
                alert('Data admin berhasil ditambahkan!');
                window.location.href = 'index.php?pages=admin';
            </script>";
            exit;
        } else {
            mysqli_query($conn, "DELETE FROM tbl_users WHERE id_user = '$id_user'");
            echo "<script>alert('Gagal Simpan Data Admin: " . addslashes($error_admin_msg ?? mysqli_error($conn)) . "'); history.back();</script>";
            exit;
        }
    } else {
        echo "<script>alert('Gagal Simpan Data User: " . addslashes($error_msg ?? mysqli_error($conn)) . "'); history.back();</script>";
        exit;
    }
}
?>

<div class="card shadow-sm border" style="border-radius: 8px;">
    <div class="card-header bg-info text-white fw-bold">
        Tambah Data Pengguna Admin
    </div>

    <div class="card-body">
        <!-- PENTING: enctype="multipart/form-data" WAJIB ADA AGAR FOTO BISA UPLOAD -->
        <form action="" method="POST" enctype="multipart/form-data">
            
            <div class="row mb-3 align-items-center">
                <label for="id-admin" class="col-sm-3 col-form-label fw-bold">ID Admin</label>
                <div class="col-sm-9">
                    <input type="text" id="id-admin" value="Otomatis" readonly class="form-control bg-light">
                </div>
            </div>

            <div class="row mb-3 align-items-center">
                <label for="id-user" class="col-sm-3 col-form-label fw-bold">ID User</label>
                <div class="col-sm-9">
                    <input type="text" id="id-user" value="Otomatis dibuat sistem (ADM000...)" readonly class="form-control bg-light">
                </div>
            </div>

            <div class="row mb-3 align-items-center">
                <label for="nama-admin" class="col-sm-3 col-form-label fw-bold">Nama Admin</label>
                <div class="col-sm-9">
                    <input type="text" id="nama-admin" name="nama_admin" class="form-control" placeholder="Nama Admin" required>
                </div>
            </div>

            <div class="row mb-3 align-items-center">
                <label for="alamat-admin" class="col-sm-3 col-form-label fw-bold">Alamat Admin</label>
                <div class="col-sm-9">
                    <textarea id="alamat-admin" name="alamat_admin" class="form-control" placeholder="Alamat Admin" rows="3" required></textarea>
                </div>
            </div>

            <div class="row mb-3 align-items-center">
                <label for="nomor-telepon" class="col-sm-3 col-form-label fw-bold">Nomor Telepon</label>
                <div class="col-sm-9">
                    <input type="text" id="nomor-telepon" name="telepon_admin" class="form-control" placeholder="Nomor Telepon Admin" required>
                </div>
            </div>

            <div class="row mb-3 align-items-center">
                <label class="col-sm-3 col-form-label fw-bold">Jenis Kelamin</label>
                <div class="col-sm-9">
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="jenis_kelamin" id="jk_l" value="L" checked>
                        <label class="form-check-label" for="jk_l">Laki-laki</label>
                    </div>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="jenis_kelamin" id="jk_p" value="P">
                        <label class="form-check-label" for="jk_p">Perempuan</label>
                    </div>
                </div>
            </div>

            <div class="row mb-3 align-items-center">
                <label for="email" class="col-sm-3 col-form-label fw-bold">Email</label>
                <div class="col-sm-9">
                    <input type="email" id="email" name="email" class="form-control" placeholder="Email" required>
                </div>
            </div>

            <div class="row mb-3 align-items-center">
                <label for="password" class="col-sm-3 col-form-label fw-bold">Password</label>
                <div class="col-sm-9">
                    <input type="password" id="password" name="password" class="form-control" placeholder="Password" required>
                </div>
            </div>

            <div class="row mb-3 align-items-center">
                <label for="password2" class="col-sm-3 col-form-label fw-bold">Confirm Password</label>
                <div class="col-sm-9">
                    <input type="password" id="password2" name="password2" class="form-control" placeholder="Confirm Password" required>
                </div>
            </div>

            <div class="row mb-3 align-items-center">
                <label for="photo-admin" class="col-sm-3 col-form-label fw-bold">Photo Admin</label>
                <div class="col-sm-9">
                    <!-- NAMA INPUT PHOTO HARUS 'photo_admin' -->
                    <input type="file" id="photo-admin" name="photo_admin" class="form-control" accept="image/*">
                </div>
            </div>

            <div class="row mb-3">
                <div class="col-sm-9 offset-sm-3">
                    <button type="submit" class="btn btn-info text-white fw-bold">Tambah</button>
                    <button type="reset" class="btn btn-danger fw-bold">Reset</button>
                    <button type="button" class="btn btn-warning text-dark fw-bold" onclick="window.location.href='index.php?pages=admin';">Cancel</button>
                </div>
            </div>

        </form>
    </div>
</div>