<?php
require_once '../../includes/config.php';

// Check if admin is logged in
if (!isAdminLoggedIn()) {
    redirect(SITE_URL . 'admin/login.php');
}

// Get user ID
$user_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($user_id <= 0) {
    redirect(SITE_URL . 'admin/users/index.php');
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = sanitize($_POST['name']);
    $email = sanitize($_POST['email']);
    $phone = sanitize($_POST['phone']);
    $address = sanitize($_POST['address']);
    $errors = [];
    
    // Validate input
    if (empty($name)) {
        $errors[] = "Nama harus diisi";
    }
    
    if (empty($email)) {
        $errors[] = "Email harus diisi";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Format email tidak valid";
    }
    
    // Update user if no errors
    if (empty($errors)) {
        try {
            $conn = connectDB();
            
            // Check if email already exists for other users
            $stmt = $conn->prepare("SELECT user_id FROM users WHERE email = :email AND user_id != :user_id");
            $stmt->bindParam(':email', $email);
            $stmt->bindParam(':user_id', $user_id);
            $stmt->execute();
            
            if ($stmt->fetch(PDO::FETCH_ASSOC)) {
                $errors[] = "Email sudah digunakan oleh pengguna lain";
            } else {
                // Update user
                $stmt = $conn->prepare("UPDATE users SET name = :name, email = :email, phone = :phone, address = :address WHERE user_id = :user_id");
                $stmt->bindParam(':name', $name);
                $stmt->bindParam(':email', $email);
                $stmt->bindParam(':phone', $phone);
                $stmt->bindParam(':address', $address);
                $stmt->bindParam(':user_id', $user_id);
                $stmt->execute();
                
                $success = "Data pengguna berhasil diperbarui";
                
                // Reset password if requested
                if (isset($_POST['reset_password']) && !empty($_POST['new_password'])) {
                    $new_password = password_hash($_POST['new_password'], PASSWORD_DEFAULT);
                    
                    $stmt = $conn->prepare("UPDATE users SET password = :password WHERE user_id = :user_id");
                    $stmt->bindParam(':password', $new_password);
                    $stmt->bindParam(':user_id', $user_id);
                    $stmt->execute();
                    
                    $success .= " dan password telah direset";
                }
            }
        } catch (PDOException $e) {
            $error = "Kesalahan: " . $e->getMessage();
        }
    }
}

try {
    $conn = connectDB();
    
    // Get user details
    $stmt = $conn->prepare("SELECT * FROM users WHERE user_id = :user_id");
    $stmt->bindParam(':user_id', $user_id);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        redirect(SITE_URL . 'admin/users/index.php');
    }
    
    $pageTitle = "Edit Pengguna: " . $user['name'];
    
} catch (PDOException $e) {
    $error = "Kesalahan: " . $e->getMessage();
}

include '../header.php';
?>

<div class="admin-header">
    <h1>Edit Pengguna</h1>
    <div class="admin-actions">
        <a href="<?php echo SITE_URL; ?>admin/users/index.php" class="btn secondary-btn">Kembali ke Daftar Pengguna</a>
        <a href="<?php echo SITE_URL; ?>admin/users/view.php?id=<?php echo $user_id; ?>" class="btn secondary-btn">Lihat Detail</a>
    </div>
</div>

<?php if (isset($success)): ?>
    <div class="success"><?php echo $success; ?></div>
<?php endif; ?>

<?php if (isset($error)): ?>
    <div class="error"><?php echo $error; ?></div>
<?php endif; ?>

<?php if (!empty($errors)): ?>
    <div class="error">
        <ul>
            <?php foreach ($errors as $err): ?>
                <li><?php echo $err; ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<div class="admin-content-box">
    <form method="post" action="" class="admin-form">
        <div class="form-group">
            <label for="name">Nama <span class="required">*</span></label>
            <input type="text" id="name" name="name" value="<?php echo $user['name']; ?>" required>
        </div>
        
        <div class="form-group">
            <label for="email">Email <span class="required">*</span></label>
            <input type="email" id="email" name="email" value="<?php echo $user['email']; ?>" required>
        </div>
        
        <div class="form-group">
            <label for="username">Username</label>
            <input type="text" id="username" value="<?php echo $user['username']; ?>" disabled>
            <small>Username tidak dapat diubah</small>
        </div>
        
        <div class="form-group">
            <label for="phone">Telepon</label>
            <input type="text" id="phone" name="phone" value="<?php echo $user['phone']; ?>">
        </div>
        
        <div class="form-group">
            <label for="address">Alamat</label>
            <textarea id="address" name="address"><?php echo $user['address']; ?></textarea>
        </div>
        
        <div class="form-section">
            <h3>Reset Password</h3>
            <p>Kosongkan jika tidak ingin mereset password</p>
            
            <div class="form-group">
                <label for="new_password">Password Baru</label>
                <input type="password" id="new_password" name="new_password">
            </div>
        </div>
        
        <div class="form-actions">
            <button type="submit" class="btn primary-btn">Simpan Perubahan</button>
            <a href="<?php echo SITE_URL; ?>admin/users/index.php" class="btn secondary-btn">Batal</a>
        </div>
    </form>
</div>

<style>
    .form-section {
        margin-top: 30px;
        padding-top: 20px;
        border-top: 1px solid #eee;
    }
    
    .form-section h3 {
        margin-top: 0;
        margin-bottom: 10px;
    }
    
    .form-section p {
        color: #666;
        margin-bottom: 20px;
        font-size: 14px;
    }
    
    .required {
        color: #e74c3c;
    }
</style>

<?php include '../footer.php'; ?> 