<?php
require_once 'config/db.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';

requireLogin();
requireAdmin();

$user_id = intval($_GET['id'] ?? 0);
if (!$user_id) { header('Location: /cash_lending/users.php'); exit(); }

$user = fetchOne($conn, "SELECT * FROM users WHERE id = ?", [$user_id], "i");
if (!$user) { header('Location: /cash_lending/users.php'); exit(); }

$errors = [];
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'update';

    if ($action === 'reset_password') {
        $new_pass    = $_POST['new_password'] ?? '';
        $confirm     = $_POST['confirm_password'] ?? '';
        if (empty($new_pass))           $errors[] = 'New password is required';
        if (strlen($new_pass) < 6)      $errors[] = 'Password must be at least 8 characters';
        if ($new_pass !== $confirm)     $errors[] = 'Passwords do not match';
        if (empty($errors)) {
            executeQuery($conn, "UPDATE users SET password = ? WHERE id = ?",
                [hashPassword($new_pass), $user_id], "si");
            logActivity($conn, $_SESSION['user_id'], 'password_reset',
                "Reset password for user: {$user['username']}");
            $success = 'Password reset successfully';
        }
    } else {
        $full_name = htmlspecialchars($_POST['full_name'] ?? '', ENT_QUOTES);
        $email     = htmlspecialchars($_POST['email']     ?? '', ENT_QUOTES);
        $phone     = htmlspecialchars($_POST['phone']     ?? '', ENT_QUOTES);
        $role      = htmlspecialchars($_POST['role']      ?? '', ENT_QUOTES);
        $is_active = isset($_POST['is_active']) ? 1 : 0;

        if (empty($full_name))                    $errors[] = 'Full name is required';
        if (empty($role))                          $errors[] = 'Role is required';
        if (!in_array($role, ['admin','staff']))   $errors[] = 'Invalid role';

        // Bug 9 & 10: prevent admin from demoting or deactivating themselves
        if ($user_id == $_SESSION['user_id']) {
            if ($role !== 'admin') $errors[] = 'You cannot change your own role.';
            if (!$is_active)      $errors[] = 'You cannot deactivate your own account.';
        }

        if (empty($errors)) {
            executeQuery($conn,
                "UPDATE users SET full_name=?, email=?, phone=?, role=?, is_active=? WHERE id=?",
                [$full_name, $email, $phone, $role, $is_active, $user_id], "ssssii");
            logActivity($conn, $_SESSION['user_id'], 'edit_user',
                "Updated user: {$user['username']}");
            header('Location: /cash_lending/users.php?success=1');
            exit();
        }
    }
    $user = fetchOne($conn, "SELECT * FROM users WHERE id = ?", [$user_id], "i");
}

include 'includes/header.php';
include 'includes/sidebar.php';
?>
<div class="row mb-4">
    <div class="col-lg-8"><h3><i class="fas fa-user-edit"></i> Edit User</h3></div>
</div>

<?php if ($success): ?>
    <div class="alert alert-success alert-dismissible fade show">
        <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>
<?php if (!empty($errors)): ?>
    <div class="alert alert-danger alert-dismissible fade show">
        <ul class="mb-0"><?php foreach($errors as $e): ?><li><?php echo htmlspecialchars($e); ?></li><?php endforeach; ?></ul>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<div class="row">
<div class="col-lg-8">
    <div class="card mb-4">
        <div class="card-header"><h5 class="mb-0">Profile Details</h5></div>
        <div class="card-body">
            <form method="POST">
                <input type="hidden" name="action" value="update">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Username</label>
                        <input class="form-control" disabled value="<?php echo htmlspecialchars($user['username']); ?>">
                        <small class="text-muted">Cannot be changed</small>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Role <span class="text-danger">*</span></label>
                        <select class="form-select" name="role" required>
                            <option value="admin" <?php echo $user['role']==='admin'?'selected':''; ?>>Admin</option>
                            <option value="staff" <?php echo $user['role']==='staff'?'selected':''; ?>>Staff</option>
                        </select>
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label">Full Name <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" name="full_name" required
                           value="<?php echo htmlspecialchars($user['full_name']); ?>">
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Email</label>
                        <input type="email" class="form-control" name="email"
                               value="<?php echo htmlspecialchars($user['email'] ?? ''); ?>">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Phone</label>
                        <input type="tel" class="form-control" name="phone"
                               value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>">
                    </div>
                </div>
                <div class="mb-3">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="is_active" id="is_active"
                               <?php echo $user['is_active'] ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="is_active">Active User</label>
                    </div>
                    <small class="text-muted">Inactive users cannot login</small>
                </div>
                <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Update User</button>
                <a href="/cash_lending/users.php" class="btn btn-outline-secondary ms-2"><i class="fas fa-times"></i> Cancel</a>
            </form>
        </div>
    </div>

    <div class="card">
        <div class="card-header bg-warning bg-opacity-10">
            <h5 class="mb-0"><i class="fas fa-key text-warning"></i> Reset Password</h5>
        </div>
        <div class="card-body">
            <form method="POST">
                <input type="hidden" name="action" value="reset_password">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">New Password <span class="text-danger">*</span></label>
                        <input type="password" class="form-control" name="new_password"
                               placeholder="Min 8 characters" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Confirm Password <span class="text-danger">*</span></label>
                        <input type="password" class="form-control" name="confirm_password"
                               placeholder="Repeat password" required>
                    </div>
                </div>
                <button type="submit" class="btn btn-warning">
                    <i class="fas fa-key"></i> Reset Password
                </button>
            </form>
        </div>
    </div>
</div>
<div class="col-lg-4">
    <div class="card">
        <div class="card-header"><h5 class="mb-0">Account Info</h5></div>
        <div class="card-body">
            <div class="mb-2"><small class="text-muted">Username</small><div><code><?php echo htmlspecialchars($user['username']); ?></code></div></div>
            <div class="mb-2"><small class="text-muted">Role</small><div><span class="badge <?php echo $user['role']==='admin'?'bg-danger':'bg-info'; ?>"><?php echo ucfirst($user['role']); ?></span></div></div>
            <div class="mb-2"><small class="text-muted">Status</small><div><span class="badge <?php echo $user['is_active']?'bg-success':'bg-secondary'; ?>"><?php echo $user['is_active']?'Active':'Inactive'; ?></span></div></div>
            <div class="mb-2"><small class="text-muted">Created</small><div><?php echo date('M d, Y', strtotime($user['created_at'])); ?></div></div>
        </div>
    </div>
</div>
</div>
<?php include 'includes/footer.php'; ?>
