<?php
// admin/users/edit.php
$pageTitle = 'Edit User';
require_once '../../includes/config.php';
require_once '../../includes/database.php';
require_once '../../includes/functions.php';
require_once '../../includes/auth.php';

// Mulai session jika belum dimulai
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Cek apakah user sudah login dan role-nya admin
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] != 'admin') {
    // Redirect ke halaman login jika belum login atau bukan admin
    setFlash('login_required', 'Anda harus login sebagai admin untuk mengakses halaman ini', 'danger');
    header('Location: ' . SITE_URL . '/auth/login.php');
    exit;
}

// Koneksi database
$db = dbConnect();

// Cek apakah ID user ada
if (!isset($_GET['id']) || empty($_GET['id'])) {
    setFlash('user', 'ID user tidak valid', 'danger');
    header('Location: ' . SITE_URL . '/admin/users/index.php');
    exit;
}

$id = $_GET['id'];

// Ambil data user berdasarkan ID
$db->query("SELECT * FROM users WHERE id = :id");
$db->bind(':id', $id);
$user = $db->single();

if (!$user) {
    setFlash('user', 'User tidak ditemukan', 'danger');
    header('Location: ' . SITE_URL . '/admin/users/index.php');
    exit;
}

// Inisialisasi variabel error
$errors = [];

// Proses form jika ada submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Ambil data dari form
    $username = sanitize($_POST['username'] ?? '');
    $nama_lengkap = sanitize($_POST['nama_lengkap'] ?? '');
    $email = sanitize($_POST['email'] ?? '');
    $no_telp = sanitize($_POST['no_telp'] ?? '');
    $alamat = sanitize($_POST['alamat'] ?? '');
    $role = sanitize($_POST['role'] ?? 'donatur');
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    // Validasi data
    if (empty($username)) {
        $errors[] = 'Username tidak boleh kosong';
    } else {
        // Cek apakah username sudah ada dan bukan milik user ini
        $db->query("SELECT id FROM users WHERE username = :username AND id != :id");
        $db->bind(':username', $username);
        $db->bind(':id', $id);
        if ($db->single()) {
            $errors[] = 'Username sudah digunakan';
        }
    }
    
    if (empty($nama_lengkap)) {
        $errors[] = 'Nama lengkap tidak boleh kosong';
    }
    
    if (empty($email)) {
        $errors[] = 'Email tidak boleh kosong';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Format email tidak valid';
    } else {
        // Cek apakah email sudah ada dan bukan milik user ini
        $db->query("SELECT id FROM users WHERE email = :email AND id != :id");
        $db->bind(':email', $email);
        $db->bind(':id', $id);
        if ($db->single()) {
            $errors[] = 'Email sudah digunakan';
        }
    }
    
    // Validasi password baru jika diisi
    if (!empty($new_password)) {
        if (strlen($new_password) < 6) {
            $errors[] = 'Password minimal 6 karakter';
        } elseif ($new_password !== $confirm_password) {
            $errors[] = 'Konfirmasi password tidak sesuai';
        }
    }
    
    // Jika tidak ada error, update data di database
    if (empty($errors)) {
        // Query dasar untuk update
        $query = "UPDATE users SET username = :username, nama_lengkap = :nama_lengkap, email = :email, no_telp = :no_telp, alamat = :alamat, role = :role";
        $params = [
            ':username' => $username,
            ':nama_lengkap' => $nama_lengkap,
            ':email' => $email,
            ':no_telp' => $no_telp,
            ':alamat' => $alamat,
            ':role' => $role,
            ':id' => $id
        ];
        
        // Tambahkan update password jika diisi
        if (!empty($new_password)) {
            $query .= ", password = :password";
            $params[':password'] = password_hash($new_password, PASSWORD_DEFAULT);
        }
        
        // Tambahkan where clause
        $query .= " WHERE id = :id";
        
        // Eksekusi query
        $db->query($query);
        foreach ($params as $param => $value) {
            $db->bind($param, $value);
        }
        
        if ($db->execute()) {
            // Log aktivitas
            logActivity('Mengubah user', 'user', $id, "Admin mengubah data user: $username ($nama_lengkap) dengan role $role");
            
            setFlash('user', 'Data user berhasil diupdate', 'success');
            header('Location: ' . SITE_URL . '/admin/users/index.php');
            exit;
        } else {
            $errors[] = 'Gagal mengupdate data user';
        }
    }
}

// Include header admin
require_once '../../includes/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <!-- Sidebar Admin -->
        <?php require_once '../../includes/sidebar-admin.php'; ?>
        
        <!-- Content Area -->
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">Edit User</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <a href="<?= SITE_URL ?>/admin/users/index.php" class="btn btn-sm btn-outline-secondary">
                        <i class="fas fa-arrow-left me-1"></i> Kembali
                    </a>
                </div>
            </div>

            <?php if (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <ul class="mb-0">
                        <?php foreach ($errors as $error): ?>
                            <li><?= $error ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>

            <!-- Form Edit User -->
            <div class="card">
                <div class="card-body">
                    <form action="" method="post">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="username" class="form-label">Username</label>
                                <input type="text" class="form-control" id="username" name="username" value="<?= isset($_POST['username']) ? $_POST['username'] : $user->username ?>" required>
                                <div class="form-text">Username harus unik dan akan digunakan untuk login.</div>
                            </div>
                            <div class="col-md-6">
                                <label for="role" class="form-label">Role</label>
                                <select class="form-select" id="role" name="role" required>
                                    <option value="donatur" <?= (isset($_POST['role']) && $_POST['role'] == 'donatur') || $user->role == 'donatur' ? 'selected' : '' ?>>Donatur</option>
                                    <option value="admin" <?= (isset($_POST['role']) && $_POST['role'] == 'admin') || $user->role == 'admin' ? 'selected' : '' ?>>Admin</option>
                                    <option value="ketua" <?= (isset($_POST['role']) && $_POST['role'] == 'ketua') || $user->role == 'ketua' ? 'selected' : '' ?>>Ketua Yayasan</option>
                                    <option value="bendahara" <?= (isset($_POST['role']) && $_POST['role'] == 'bendahara') || $user->role == 'bendahara' ? 'selected' : '' ?>>Bendahara</option>
                                    <option value="sekretaris" <?= (isset($_POST['role']) && $_POST['role'] == 'sekretaris') || $user->role == 'sekretaris' ? 'selected' : '' ?>>Sekretaris</option>
                                    <option value="pengawas" <?= (isset($_POST['role']) && $_POST['role'] == 'pengawas') || $user->role == 'pengawas' ? 'selected' : '' ?>>Pengawas</option>
                                </select>
                                <div class="form-text">Pilih role user sesuai dengan fungsinya dalam sistem.</div>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="nama_lengkap" class="form-label">Nama Lengkap</label>
                                <input type="text" class="form-control" id="nama_lengkap" name="nama_lengkap" value="<?= isset($_POST['nama_lengkap']) ? $_POST['nama_lengkap'] : $user->nama_lengkap ?>" required>
                            </div>
                            <div class="col-md-6">
                                <label for="email" class="form-label">Email</label>
                                <input type="email" class="form-control" id="email" name="email" value="<?= isset($_POST['email']) ? $_POST['email'] : $user->email ?>" required>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="no_telp" class="form-label">Nomor Telepon</label>
                                <input type="text" class="form-control" id="no_telp" name="no_telp" value="<?= isset($_POST['no_telp']) ? $_POST['no_telp'] : $user->no_telp ?>">
                            </div>
                            <div class="col-md-6">
                                <label for="alamat" class="form-label">Alamat</label>
                                <textarea class="form-control" id="alamat" name="alamat" rows="3"><?= isset($_POST['alamat']) ? $_POST['alamat'] : $user->alamat ?></textarea>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="new_password" class="form-label">Password Baru</label>
                                <input type="password" class="form-control" id="new_password" name="new_password">
                                <div class="form-text">Kosongkan jika tidak ingin mengubah password.</div>
                            </div>
                            <div class="col-md-6">
                                <label for="confirm_password" class="form-label">Konfirmasi Password</label>
                                <input type="password" class="form-control" id="confirm_password" name="confirm_password">
                                <div class="form-text">Kosongkan jika tidak ingin mengubah password.</div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-12">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save me-1"></i> Update
                                </button>
                                <a href="<?= SITE_URL ?>/admin/users/index.php" class="btn btn-secondary">
                                    <i class="fas fa-times me-1"></i> Batal
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </main>
    </div>
</div>

<?php require_once '../../includes/footer.php'; ?>